Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Conditions apply colours to a drawing
Conditional rendering is used when we need to render different front-end pages according to different conditions. Vue provides us with v-if, V-else -if, v-else methods.
practice
code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">Please enter your grade:<input v-model="type">
<br>
<p>You type: {{type}}</p>
<div v-if="type=='C'">
<h1>Pass the</h1>
</div>
<div v-else-if="type=='A'">
<h1>good</h1>
</div>
<div v-else>
<h1>Don't pass the</h1>
</div>
</div>
<script>
app = new Vue({
el: "#app".data: {
type: "C"}})</script>
</body>
</html>
Copy the code
Effect of the page
The original:
After entering A:
Enter other values:
Tips
v-model
The binding of input box content and data is realized.v-if
According to the data of different values to display different content.- in
v-if
There are single quotes inside the double quotes in the template.
Another way to render conditional
In the above form, v-if is directly written in the page to determine the condition, which is not very elegant. We try to use the dictionary to render different values according to different keys to modify.
code
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">Please enter your grade:<input v-model="type" placeholder="Please enter the correct level! (A,B,C,D)">
<br>
<p>You type: {{type}}</p>
<h2>{{ res[type] }}</h2>
</div>
<script>
app = new Vue({
el: "#app".data: {
type: "C".res: {"C":"Pass"."A":"Good"."B":"Good"."D":"Fail"}}})</script>
</body>
</html>
Copy the code
Effect of the page
The original:
Input A:
Type D:
We found that page code was more elegant in the way dictionaries were used for determinable conditions and results. However, v-if is also very rarely used.
That’s all for today, thank you for reading, and we’ll see you next time.