前言
介绍Vue3的条件语句、循环语句
准备组件
components下新增SentenseTest.vue
App.vue引进以上的主键
import SentenseTest from './components/SentenseTest.vue'
<SentenseTest/>
export default {
name: 'App',
components: {
HelloWorld,
SentenseTest
},
mounted(){
this.$refs.hello_world.changeHello();
}
}
1、条件语句
1.1、v-if
<div v-if="seen">
v-if 测试
</div>
export default{
name: 'SentenseTest',
data(){
return{
seen : true
}
}
}
1.2、v-else
<div v-if="seen">
v-if 测试
</div>
<div v-else>
v-else 测试
</div>
结果:
1.3、v-else-if
<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>
其他等级
</div>
export default{
name: 'SentenseTest',
data(){
return{
type : "A"
}
}
}
结果:
1.4、v-show
根据条件展示元素。
<h1 v-show="seen">
显示或隐藏
</h1>
export default{
name: 'SentenseTest',
data(){
return{
seen : true
}
}
}
结果:
2、循环语句
循环使用 v-for 指令。
2.1、遍历数组
<table border="1">
<caption><b>名单</b></caption>
<th>序号</th><th>姓名</th><th>性别</th>
<tr v-for="(userInfo,index) in userInfos" :key="index">
<td>{{index + 1}}</td><td>{{userInfo.name}}</td><td>{{userInfo.gender}}</td>
</tr>
</table>
export default{
name: 'SentenseTest',
data(){
return{
userInfos : [
{"name":"tiger","gender":"male"},
{"name":"cat","gender":"male"},
{"name":"mouse","gender":"female"},
{"name":"lion","gender":"female"}
]
}
}
}
结果:
2.2、迭代对象
<ol>
<li v-for="(value,key,index) in userInfo" :key="index">
{{key}} | {{value}} | {{index}}
</li>
</ol>
export default{
name: 'SentenseTest',
data(){
return{
userInfo : {"id":23423,"orderNo":"sn001","amount":88.2,"createDate":"2023-02-20"
}
}
}
}
结果:
2.3、显示过滤/排序后的结果
<ol>
<li v-for="n in eventNumbers" :key="n">
{{n}}
</li>
</ol>
export default{
name: 'SentenseTest',
data(){
return{
numbers:[5,3,2,6,90]
}
},
computed:{
eventNumbers(){
return this.numbers.filter(number => number % 2 === 0)
}
}
}
2.4、v-for/v-if 联合使用
<select @change="changeVal($event)" v-model="selectOption">
<template v-for="(orderStatus,index) in orderStatuses" :key="orderStatus.code" >
<option v-if="index == 1" :value="orderStatus.code" selected>{{orderStatus.name}}</option>
<option v-else :value="orderStatus.code" >{{orderStatus.name}}</option>
</template>
</select>
<div>{{selectOption}}</div>
export default{
name: 'SentenseTest',
data(){
return{
selectOption:1,
orderStatuses:[
{"code":1,"name":"待支付"},
{"code":2,"name":"已支付"},
{"code":3,"name":"已取消"},
{"code":4,"name":"已完成"}
]
}
},
methods:{
changeVal:function(event){
this.selectOption = event.target.value;
alert(this.selectOption);
}
}
}
结果: