Vue中的变更方法与替换数组
变更方法push()、pop()、shift()、unshift()splice()sort()reverse()会变更原始数组,所以页面上的数据会发生变化(触发视图更新)。替换数组filter()concat()slice()不会变更原始数组,所以页面上的数据不会发生变化。<div id='box'><ul><li v-for='(item,index) in bo
·
变更方法
- push()、pop()、shift()、unshift()
- splice()
- sort()
- reverse()
会变更原始数组,所以页面上的数据会发生同步变化(触发视图更新)。
替换数组
- filter()
- concat()
- slice()
不会变更原始数组,所以页面上的数据不会发生同步变化。
<div id='box'>
<ul>
<li v-for='(item,index) in books'>{{item}}</li>
</ul>
<button @click='del'>删除数组元素pop</button>
<button @click='change'>截取数组元素slice</button>
</div>
var vm = new Vue({
el: '#box',
data: {
books: ['html', 'css', 'js', 'c++', 'java']
},
methods: {
del: function() {
this.books.pop();
},
change: function() {
//截取数组的元素,索引为[0-2)
// this.books.slice(0, 2);//这样无法截取,因为books数组本身并没有发生变化
this.books = this.books.slice(0, 2);//将截取的结果赋值给books
}
}
})
效果:
动态响应式更改数组或对象中某一项的值
- Vue.set(vm.items, indexOfItem, newValue)
- vm.$set(vm.items, indexOfItem, newValue)
① 参数一表示要处理的数组名称
② 参数二表示要处理的数组的索引
③ 参数三表示要处理的数组的值
var vm = new Vue({
el: '#app',
data: {
list: ['apple', 'orange', 'banana'],
info: {
name: 'lisi',
age: 12
}
},
});
// Vue.set(vm.list, 2, 'lemon');
vm.$set(vm.list, 1, 'lemon');
vm.$set(vm.info, 'gender', 'female');
更多推荐
已为社区贡献2条内容
所有评论(0)