Reputation: 1205
Is it possible to use ternary condition in a Vue template to return HTML, similar to React render function?
<some-vue-component :someProp="someVal" />
This doesn't seem to work:
// some-vue-component template file
{{someProp == true ? <h1>Hello</h1> : <h1>Bye</h1>}}
Do I need to use v-if
?
// some-vue-component template file
<div>
<div v-if="someProp === true">
<h1>Hello</h1>
</div>
<div v-else>
<h1>Bye</h1>
</div>
</div>
Upvotes: 10
Views: 14993
Reputation: 29092
Everything output using {{ ... }}
will be escaped, so you can't include HTML tags.
In the example you gave you'd just move the <h1>
outside the {{ ... }}
:
<h1>{{ someProp ? 'Hello' : 'Bye' }}</h1>
More generally you'd use v-if
:
<h1 v-if="someProp">Hello</h1>
<h2 v-else>Bye</h2>
Note also that v-if
can be placed on a <template>
tag if you don't want it to add an extra element to the finished DOM:
<template v-if="someProp">Hello</template>
<strong v-else>Bye</strong>
At a pinch there's also v-html
but you should avoid using that if at all possible. It allows you to inject HTML directly but that's rarely necessary as templates can handle the vast majority of use cases.
Upvotes: 22