一、条件渲染
- 相关指令
v-if
<p v-if="tag === 'A'">这里是A</p>
v-else-if
<p v-else-if="tag === 'C'">这里是C</p>
v-else
<p v-else>这里什么也没有</p>
- 控制多个元素
<button @click="changels">切换</button>
- 复用元素
Vue为了高效渲染元素,一般会选择复用已存在的元素,而不是从新渲染,如果想每次都重新渲染,那么就给标签一个唯一值的key属性
<template v-if="isUserLogin">
<label>用户名</label>
<input type="text" placeholder="请输入用户名" key="userLoginForm">
</template>
<template v-else>
<label>邮箱</label>
<input type="text" placeholder="请输入邮箱" key="emailLoginForm">
</template>
<br>
<button @click="isUserLogin = !isUserLogin">更换登录方式</button>
- v-show
<p v-show="is">哈哈哈</p>
v-if是真正的条件渲染
v-show只是判断是否将标签隐藏
二、列表渲染
- 遍历数组
<ul>
<li v-for="(num,index) in numList" :key="index">{{index}}:{{ num }}</li>
</ul>
- 遍历对象
<ul>
<li v-for="(item,key,index) in person">{{index}} - {{key}}:{{ item }}</li>
</ul>
- 使用this.$set()或者Vue.set()对数组及对象进行内容的修改
var app =new Vue ({
el:'#app',
data:{
title:'Vue列表渲染',
numList:['一','二','三','四','五','六','七','八'],
person:{name:'李白',age:'45',address:'长安'},
number:100,
nameList:[
{name:'松江',isActive:true},
{name:'李辉',isActive:false},
{name:'小明',isActive:true},
{name:'笑话',isActive:true}
]
},
methods:{
changeNumList: function() {
this.numList.push('十五');管用
this.numList.reverse();管用
this.numList.sort();管用
this.numList='李逵';没用
this.$set(this.numList,4,'李逵');管用
Vue.set(this.numList,4,'李逵');管用
this.numList.length=5;没用
this.numList.splice(5);管用
},
changePerson: function() {
this,person.age = 100;管用
delete this.person;没用
this.person.email = 'libai@qq.com';没用
Vue.set(this.person,'email','libai@qq.com');管用
this.person= {name:'杜甫'}管用
}
}
})
- 遍历数字
<div>
<span v-for="n in 10">{{ n }}</span>
</div>
- 重复多条内容
<ul>
<!-- template 不具体实现 -->
<template v-if="item in items">
<li>{{item.msg}}</li>
<li class="divder" role="presentation"></li>
</template>
</ul>
- v-for与v-if同时使用,v-for优先级高
v-for 与 v-if同时使用,v-for的优先级高
<li v-for="todo in todos" v-if="!todo.isComplete">
{{todo}}
</li>