如何在 v-html 和 vue.js 中作为纯文本插入?

ome*_*ega 2 javascript vue.js

我希望在 v-html 和作为纯文本插入 vue.js v2 之间切换。到目前为止我有这个

HTML

<div id="app">
  <h2 v-html="html ? text : undefined">{{html ? '' : text}}</h2>
  <button @click="toggle">
    switch
  </button>
</div>
Run Code Online (Sandbox Code Playgroud)

JS

new Vue({
  el: "#app",
  data: {
    text:"Hello<br/>World",
    html:false
  },
  methods: {
    toggle: function(){
        this.html = !this.html;
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

但这在htmlfalse时不起作用。我怎样才能让它发挥作用?我正在寻找一种解决方案,我不需要<h2>使用v-else. 最好,如果我可以只用 1<h2>标签做到这一点。

谢谢

Ste*_* B. 5

v-bindprop修饰符一起使用。 请参阅文档

new Vue({
  el: "#app",
  data: {
    text:"Hello<br/>World",
    html:false
  },
  computed: {
    headingProps() {
      return this.html ? { innerHTML: this.text } : { innerText: this.text } ;
    },
  },
  methods: {
    toggle: function(){
        this.html = !this.html;
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <h2 v-bind.prop="headingProps"></h2>
  <button @click="toggle">
    switch
  </button>
</div>
Run Code Online (Sandbox Code Playgroud)