2

I'm looking to toggle between v-html and insert as plain text in vue.js v2. So far I have this

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

but this doesn't work when html is false. How can I get this to work? I'm looking for a solution where I don't need to repeat <h2> twice using a v-else. Preferably, if I can do it with just the 1 <h2> tag.

Thanks

1 Answer 1

5

Use v-bind with the prop modifier. 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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.