Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue.js Conditional Statements

Vue.js Conditional Statements

Conditional Judgment

v-if

Conditional judgment uses the v-if directive:

v-if Directive

Use the v-if directive in elements and template:

<div id="app">
<p v-if="seen">

Now you see me

p

<

template

v-if

=

"

ok

"

<

h1

Runoob Tutorial

h1

<

p

What you learn is not only technology, but also a dream!

p

<

p

Haha, typing is hard work!!!

p

template

div

<

script

new Vue({ el: '#app', data: { seen: true, ok: true } })

script

Try it »

Here, the v-if directive will decide whether to insert the p element based on the value of the expression seen (true or false).

In string templates, such as Handlebars, we have to write a conditional block like this:





{{#if ok}}

  

Yes

{{/if}}

v-else

You can use the v-else directive to add an "else" block to v-if:

v-else Directive

Randomly generate a number, determine whether it is greater than 0.5, and then output the corresponding message:

<div id="app">
<div v-if=">

Math.random() > 0.5

"

Sorry

div

<

div

v-else

Not sorry

div

div

<

script

new Vue({ el: '#app' })

script

Try it »

v-else-if

v-else-if was added in 2.1.0; as the name implies, it serves as the else-if block for v-if. It can be chained multiple times:

v-else Directive

Judge the value of the type variable:

<div id="app">
<div v-if=">

type === 'A'

"

A

div

<div v-else-if=">

type === 'B'

"

B

div

<div v-else-if=">

type === 'C'

"

C

div

<

div

v-else

Not A/B/C

div

div

<

script

new Vue({ el: '#app', data: { type: 'C' } })

script

Try it »

v-else and v-else-if must follow v-if or v-else-if.

v-show

We can also use the v-show directive to show elements based on a condition:

v-show Directive

<h1 v-show="ok">

Hello!

h1

Try it »