Vue.js conditions and loops

Source: Alibaba cloud University - Developer class - Vue.js self study manual Conditional judgement v-if Condition judgment uses v-if instruction: v-...


Source: Alibaba cloud University - Developer class - Vue.js self study manual

Conditional judgement

v-if

Condition judgment uses v-if instruction:

v-if directive

Use the v-if directive in the element and template:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue Test case - Alicloud University(/edu.aliyun.com)</title> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> </head> <body> <div id="app"> <p v-if="seen">Now you see me</p> <template v-if="ok"> <h1>Alicloud University</h1> <p>What we learn is not only technology, but also dream!</p> <p>Ha ha what, typing hard!!!</p> </template> </div> <script> new Vue({ el: '#app', data: { seen: true, ok: true } }) </script> </body> </html>

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

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

<!-- Handlebars Template --> {{#if ok}} <h1>Yes</h1> {{/if}}


v-else

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

v-else instruction

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

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue Test case - Alicloud University(edu.aliyun.com)</title> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> </head> <body> <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> </body> </html>

Operation result

Sorry


v-else-if

v-else-if is added in 2.1.0. As the name implies, it is used as the else if block of v-if. It can be used many times in chain:

v-else instruction

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

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vue Test case - Alicloud University(edu.aliyun.com)</title> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script> </head> <body> <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> </body> </html>

V-else, v-else-if must follow v-if or v-else-if.

v-show

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

v-show instruction

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

Note: v-show does not support < template > syntax.

Come from: Alibaba cloud University - Developer class - Vue.js self study manual


1 November 2019, 16:34 | Views: 8185

Add new comment

For adding a comment, please log in
or create account

0 comments