1、v-for数组渲染列表
用v-for将一个数组渲染为列表
<div id="app">
<div v-for="item in items">
{{item.text}}{{wenben}}
</div>
//这里的v-for块中,能够对父作用域进行访问
</div>
var vm = new Vue({
el: '#app',
data:{
wenben:'hello',
//在父作用域中创建一个属性,若能被渲染则证明v-for能够对父作用域进行访问
items:[
{text:"chifan",isOk:true},
{text:"shuijiao",isOk:false},
{text:"kandianshi",isOk:true},
{text:"watch tv",isOk:true},
{text:"kandianying",isOk:false},
]
}
});
运行结果:
v-for 还支持一个可选的第二个参数,即当前项的索引。
<div id="app">
<div v-for="(item,index) in items">
//1、这里的index是v-for的第二个参数,即当前项的索引值
//2、这里的in可以用of来代替
{{index+1}}{{item.text}}{{wenben}}
</div>
</div>
运行结果可以将索引值渲染上去:
2、v-for把对象属性渲染成列表
<div id="app">
<div v-for="(value,key,index) in nana">
//第二个参数为键名,第三个参数为索引值
{{index}}{{key}} is {{value}}
</div>
</div>
创建一个nana的对象,用v-for进行渲染
var vm = new Vue({
el: '#app',
data:{
nana: {
firstName: 'John',
lastName: 'Doe',
age: 30
}
}
});
运行结果:
3、v-for渲染组件列表
在自定义组件上,你可以像在任何普通元素上一样使用 v-for
。
定义一个组件:
Vue.component("todo-item",{
template:'<div><input type="button" value="X"/></div>'
})
接下来将列表中的数据传给组件,利用v-bind来实现
<div id="app">
<todo-item v-for="item in items" v-bind:tiaomu="item.text"></todo-item>
</div>
在组件中要使用props来注册一个tiaomu
的属性才能将列表数据传入到组件里
Vue.component("todo-item",{
template:'<div>{{this.tiaomu}}<input type="button" value="X"/></div>',
props:['tiaomu'],
})
var vm = new Vue({
el:"#app",
data:{
items:[
{text:"芜湖",isOk:true},
{text:"芜湖",isOk:true},
{text:"芜湖",isOk:true},
{text:"芜湖",isOk:true},
{text:"芜湖",isOk:true},
]
},
})
运行结果:
注意:2.2.0+ 的版本里,当在组件上使用 v-for 时,key 现在是必须的。
所以应该改进为:
<div id="app">
<todo-item v-for="(item,index) in items" v-bind:tiaomu="item.text" :key="index"></todo-item>
</div>
4、取值范围_template_排序过滤
在 v-for 里使用值范围
<div >
<span v-for="n in 10">{{ n }} </span>
</div>
结果输出1-10的数字
在 <template>
上使用 v-for
<div id="app">
<ul>
<template v-for="item in items">
<li>{{ item.msg }}</li>
<li class="divider"></li>
</template>
</ul>
</div>
<style>
.divider{
list-style-type: none;
border-bottom: 1px solid red;
}
</style>
var vm = new Vue({
el: '#app',
data:{
items:[
{msg:"abc1"},
{msg:"abc2"},
{msg:"abc3"},
{msg:"abc4"}
]
})
运行结果:
显示过滤/排序后的结果
显示一个数组中的偶数
<div id="app">
<div v-for="num in even()">{{num}}</div>
</div>
var vm = new Vue({
el: '#app',
data:{
numbers: [ 1, 2, 3, 4, 5 ]
},
computed:{
evenNum:function(){
return this.numbers.filter(function(item){
return item%2==0;
//这里item需要被2整除来判断偶数
});
}
},
});
同样,当计算属性不适用时,也可以使用method方法来实现同样的效果
var vm = new Vue({
el: '#app',
data:{
numbers: [ 1, 2, 3, 4, 5 ]
},
methods:{
even:function(){
return this.numbers.filter(function(item){
return item%2==0;
});
}
}
});
运行结果:
5、数组更新的检测
变更方法:(能够被vue检测到的数组变更方法,会触发视图的更新)
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
替换数组
不会变更原始数组,而总是返回一个新数组。当使用非变更方法时,可以用新数组替换旧数组:
filter()
concat()
slice()