Vuejs将HTML转换为纯文本

时间:2017-10-06 05:34:05

标签: javascript html css vue.js

我想使用vuejs将HTML转换为纯文本。

<ol>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
</ol>

我使用了v-html但是这样解析HTML就像下面的HTML一样

 1. The quick brown fox jumps over the lazy dog
 2. The quick brown fox jumps over the lazy dog 
 3. The quick brown fox jumps over the lazy dog
 4. The quick brown fox jumps over the lazy dog

但我希望结果是这样的。

The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dog

我可以使用angularjsjavascript执行此操作,但我找不到vuejs

的任何内容

注意:我在项目中没有使用jquery

2 个答案:

答案 0 :(得分:2)

自定义指令

&#13;
&#13;
Vue.directive('plaintext', {
  bind(el, binding, vnode) {
    el.innerHTML = el.innerText;
    //el.innerHTML = el.innerHTML.replace(/<[^>]+>/gm, '');
  }
});

new Vue({
  el: "#app"
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">

  <ol v-plaintext>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
  </ol>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试从css转换

var vm = new Vue({
  el: '#vue-instance',
  data: {
    html: `<ol>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
</ol>` 
  }
});
ol{
  list-style: none;
}
ol li{
  display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<div id="vue-instance">
  <div v-html="html"></div>
</div>

使用隐藏div的另一种方式

var vm = new Vue({
  el: '#vue-instance',
  computed:{
    newHTML: function(){
      document.querySelector("#temp").innerHTML = this.html;
      var textContent = document.querySelector("#temp").textContent;
      document.querySelector("#temp").innerHTML = "";
      return textContent;
    }
  },
  data: {
    html: `<ol>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
    <li>The quick brown fox jumps over the lazy dog</li>
</ol>`
  }
});
.hide{
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<div id="vue-instance">
  <div>{{newHTML}}</div>
</div>
<div class="hide" id='temp'>123</div>