1、v-for
v-for
可以迭代数组,对象数组,对象,数字;第几次迭代是可选项。
-
v-for
中使用key
属性– 在v-for循环中,如果使用v-for存在问题,需要使用key将每项唯一标识
– key属性只能使用v-bind绑定 number 或 string
示例:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="lib/vue-2.4.0.js"></script>
</head>
<body>
<div id="app">
<!-- 1.遍历普通数组 -->
<p v-for="item in list1">{{item}}</p>
<p v-for="(item, i) in list2">索引值: {{i}} 内容: {{item}}</p>
<hr>
<!-- 2.遍历对象数组 -->
<p v-for="user in list2">Id: {{user.id}} --- name: {{user.name}}</p>
<p v-for="(user, i) in list2">Index: {{i}} == Id: {{user.id}} == name: {{user.name}}</p>
<hr>
<!-- 3.遍历对象属性 -->
<!-- 注意: 属性值的顺序 (值, 属性, [索引]) -->
<p v-for="(value, key) in user">属性: {{key}} == 值: {{value}}</p>
<p v-for="(value, key, index) in user">索引: {{index}} == 属性: {{key}} == 值: {{value}}</p>
<hr>
<!-- 4.迭代数字 -->
<!-- 注意: 迭代数字,从1开始计数到5,即[1, 5] -->
<p v-for="count in 5">这是第 {{count}} 次循环</p>
<hr>
<!-- 5. v-for中的key唯一标识项 -->
<div>
<label>Id:
<input type="text" v-model="id">
</label>
<label>Name:
<input type="text" v-model="name">
</label>
<input type="button" value="添加" @click="add">
</div>
<p v-for="item in list2" :key="item.id">
<input type="checkbox"> {{item.id}} --- {{item.name}}
</p>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
id: '',
name: '',
list1: [1, 2, 3, 4, 5, 6],
list2: [
{id: 1, name: 'John'},
{id: 2, name: 'Alice'},
{id: 3, name: 'Bob'},
{id: 4, name: 'Tom'}
],
user: {
id: 1,
name: 'King',
gender: 'man'
}
},
methods: {
add(){
this.list2.unshift( { id: this.id, name: this.name } )
}
}
});
</script>
</body>
</html>
2、v-if & v-show
两个指令都是用于判断是否显示当前标签。
v-if
: 每次都会重新删除或创建元素,有较高的切换性能消耗
v-show
: 每次只是添加或移除 display:none 样式,有较高的初始渲染消耗,需要频繁切换时用到
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="lib/vue-2.4.0.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="函数名" @click="toggle">
<input type="button" value="表达式" @click="flag=!flag">
<h3 v-if="flag">忆及童年,芦村,三更之夜</h3>
<h3 v-show="flag">青蛙叫喊, 到处是春暮之火</h3>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
flag: true
},
methods: {
toggle(){
this.flag = !this.flag
}
}
});
</script>
</body>
</html>