29

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?

1

2 Answers 2

63

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>

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

1 Comment

It's the best answer regarding the asked question. So I upvoted it. But a good practice would be to NOT return HTML. Regarding this, @JeBokE answer is "better".
7

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>

1 Comment

It's one way to do it, but it's far from optimal. Vue discourages template handled directly into thi HTML.

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.