Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ternary in Vue Template

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>
like image 908
henhen Avatar asked Aug 19 '19 04:08

henhen


1 Answers

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.

like image 108
skirtle Avatar answered Sep 21 '22 18:09

skirtle