javascript - 如何在 v-html 之间切换并在 vue.js 中以纯文本形式插入?

标签 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>

JS

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

但是这在 html 时不起作用是假的。我怎样才能让它工作?我正在寻找不需要重复的解决方案 <h2>两次使用 v-else .最好是,如果我能用 1 <h2> 做到这一点标签。

谢谢

最佳答案

使用 v-bindprop 修饰符。 see docs .

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;
    }
  }
})
<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>

关于javascript - 如何在 v-html 之间切换并在 vue.js 中以纯文本形式插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67422352/

相关文章:

node.js - 从 expressJS (sendFile) 服务器下载文件到 VueJS,是否返回损坏的文件?

vue.js - 我有一个 Electron 项目,我想与它一起使用vueJS

javascript - 对象字面量作为原型(prototype)

javascript - Meteoor 中样式表的内容类型

javascript - javascript 应用程序中的背景亚克力背景

javascript - 为什么我的总乘数为每个答案添加了 2 的模式?

javascript/jquery getImageData 图像颜色选择

javascript - 通过 Javascript 功能实时编辑 HTML

javascript - 在 Vue&Vuex 中,如何激活子组件中的 onclick 方法?

vue.js - Vue.js : cannot redefine property: $url