netdjw
netdjw

Reputation: 5997

How to handle when VueJS computed properties return HTML code?

I use VueJS 2 to render and calculate form items. Now I need to show a number if a propertie is under 10, and I need show a text message if the propertie is over or equal 10.

I use this code:

Vue.component('mycomponent', {
    template: '#mytemp',
    data: function() {
        // ...
    },
    computed: {
         mycomputedprop: function() {
             if (this.model_a < 10) {
                 return '<span class="numbervalue">' + this.model_a + '€</span>';
             } else {
                 return '<span class="textvalue">I\'ll contact you as soon as possible!</span>';
             }
         }
    }
});

I use this code to show the value:

<div id="app">
    {{ mycomputedprop }}
</div>

The problem is: if I show this value it shows the HTML code as text, not as HTML. How can I show the returned value as a HTML code?

Upvotes: 28

Views: 51958

Answers (2)

Mohammad Fanni
Mohammad Fanni

Reputation: 4173

You could use v-html

Document : Raw-HTML

<div id="app">
 <div v-html="mycomputedprop"></div>
</div>

The contents of this div will be replaced with the value of the rawHtml property, interpreted as plain HTML - data bindings are ignored. Note that you cannot use v-html to compose template partials, because Vue is not a string-based templating engine. Instead, components are preferred as the fundamental unit for UI reuse and composition.

Vue 3 Example:

const RenderHtmlApp = {
  data() {
    return {
      rawHtml: '<span style="color: red">This should be red.</span>'
    }
  }
}

Vue.createApp(RenderHtmlApp).mount('#example1')
<script src="https://unpkg.com/vue@next"></script>
<div id="example1">
    <p>Using mustaches: {{ rawHtml }}</p>
    <p>Using v-html directive: <span v-html="rawHtml"></span></p>
</div>

Upvotes: 62

Djurdjen
Djurdjen

Reputation: 283

Assuming that modal_a is defined in the data of your component, why not handle this within the component template?

  <div id="app">
    <span v-if="model_a < 10" class="numbervalue">{{model_a}} €</span>
    <span v-else class="textvalue">I\'ll contact you as soon as possible!</span>
  </div>

Upvotes: 7

Related Questions