vue 数组方法
数组更新
vue的核心时数据和视图的双向绑定,当我们修改数组时,vue会检测到数据的变化,所以用v-for渲染的视图也会立即更新。vue包含了一组观察数组变异的方法,使用它们改变数组也会触发视图更新:
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
<div id="app"> <ul> <template v-for="book in books"> <li>书名:{{ book.name }}</li> <li>作者:{{ book.author }}</li> </template> </ul> </div> <script> var app = new Vue({ el:'#app', data: { books: [ { name: 'vuejs', author: 'liang' }, { name: 'javascript', author: 'douglas' }, { name: 'nodejs', author: 'thomas' } ] } }); app.books.push({ name:'css', author: 'dsss' }); </script>
使用以上方法会改变被这些方法调用的原始数组,有些地方不会改变原始数组,例如:
- filter()
- concat()
-
slice()
<div id="app"> <ul> <template v-for="book in books"> <li>书名:{{ book.name }}</li> <li>作者:{{ book.author }}</li> </template> </ul> </div> <script> var app = new Vue({ el:'#app', data: { books: [ { name: 'vuejs', author: 'liang' }, { name: 'javascript', author: 'douglas' }, { name: 'nodejs', author: 'thomas' } ] } }); app.books = app.books.filter(function (item) { return item.name.match(/javascript/); }) </script>
vue在检测数组变化时,并不是直接重新渲染整个列表,而是最大化地复用DOM元素。替换的数组中,含有相同元素的项不会被重新渲染,因此可以大胆地用新数组来替换旧数组,不用担心性能问题。
通过一个数组的副本来做过滤或排序的显示时,可以使用计算属性来返回过滤或排序后的数组,并且不改变原数组。
<div id="app">
<ul>
<template v-for="book in filterBooks">
<li>书名:{{ book.name }}</li>
<li>作者:{{ book.author }}</li>
</template>
</ul>
</div>
<script>
var app = new Vue({
el:'#app',
data: {
books: [
{
name: 'vuejs',
author: 'liang'
},
{
name: 'javascript',
author: 'douglas'
},
{
name: 'nodejs',
author: 'thomas'
}
]
},
computed: {
filterBooks: function () {
return this.books.filter(function (book) {
return book.name.match(/javascript/);
});
}
}
});
</script>
实现排序也是类似的,新加一个计算属性sortedBooks,按照书名的长度由长到短进行排序
computed: {
sortedBooks: function () {
return this.books.sort(function (a,b) {
return a.name.length < b.name.length;
});
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: