Vue3 conditional statement


Release date:2024-03-06 Update date:2024-03-08 Editor:admin View counts:145

Label:

Vue3 conditional statement

Conditional judgment

v-if

The conditional judgment uses the v-if instruction, and the expression of the instruction will only be displayed when it returns true :

v-if instruction

Use in an element v-if directive:

<divid="app"><pv-if="seen">Now you see me</p></div><script>const app = {
data() { return { seen: true /\* Change to false, the information cannot be displayed \*/ } } }
Vue.createApp(app).mount('#app')</script>

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

Because v-if is an instruction, it must be added to an element. If there are multiple elements, they can be wrapped around the <template> element, the final rendering result will not contain any <template> elements. And use v-if on top. The final rendering result will not include the <template> element.

v-if instruction

In <template> element using the v-if directive:

<divid="app"><templatev-if="seen"><h1>website</h1><p>Google</p><p>Runoob</p><p>Taobao</p></template></div><script>const
app = { data() { return { seen: true /\* Change to false, the information cannot be displayed \*/ }
} } Vue.createApp(app).mount('#app')</script>

v-else

You can use the v-else instruction to add an “else” block to the v-if :

v-else instruction

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

<divid="app"><divv-if="Math.random() > 0.5">Random number greater than
0.5</div><divv-else>Random number less than or equal to
0.5</div></div><script>Vue.createApp(app).mount('#app')</script>

v-else-if

v-else-if that is, v-if of else-if block, which can be used many times in chain:

v-else instruction

Determine the value of the variable type :

<divid="app"><divv-if="type === 'A'">A</div><divv-else-if="type ===
'B'">B</div><divv-else-if="type === 'C'">C</div><divv-else>Not
A/B/C</div></div><script>const app = { data() { return { type: "C" } } }
Vue.createApp(app).mount('#app')</script>

v-elsev-else-if have to follow. v-if or v-else-if After that.

v-show

We can also use v-show directive to display elements according to conditions:

v-show instruction

<h1v-show="ok">Hello!</h1>

Powered by TorCMS (https://github.com/bukun/TorCMS).