Vico
Vico

Reputation: 1256

Conditional V-HTML rendering

Just wondering if there is something I'm missing here:

<span v-html="(shouldParseHTMLBool ? HTMLContent : '')">
  {{ contentWithoutParsedHTML }}
</span>

doens't appear to work.

I would like to have this span interpreting HTML only if shouldParseHTMLBool is set to true.

Is it something possible, or should I use a v-if? In this trivial example it's not a big deal, but with my components I'll have to duplicate ~30 lines for each condition.

Upvotes: 2

Views: 4708

Answers (3)

Farhat Aziz
Farhat Aziz

Reputation: 146

try this

<span v-if="shouldParseHTMLBool" v-html="HTMLContentForIfCondition" >All</span>
<span v-else v-html="HTMLContentForElseCondition" ></span>

You can use two spans, One for v-if is true and other for v-else

Upvotes: 0

eli-bd
eli-bd

Reputation: 1634

The v-html directive replaces the innerHTML of the element. In your case, the {{ contentWithoutParsedHTML }} will be replaced with the value of (shouldParseHTMLBool ? HTMLContent : '')

You can do something like

<template>
<span v-html="conditionalParse"></span>
</template>
<script>
methods: {
conditionalParse: function () {
    return this.shouldParseHTMLBool ? this.HTMLContent : ''
}
</script>

Upvotes: 0

Yozz
Yozz

Reputation: 485

It's better to make if condition away from template as much as possible. You should create a computed object instead.

[template]

<span v-html="computedContent"></span>

[script]

...
computed: {
  computedContent: function () {
    return this.shouldParseHTMLBool ? this.HTMLContent : ''
  }
},
...

Upvotes: 2

Related Questions