变异方法 (mutation method),顾名思义,会改变被这些方法调用的原始数组。相比之下,也有非变异 (non-mutating method) 方法,例如:
filter()
,concat()
和slice()
。这些不会改变原始数组,但总是返回一个新数组。当使用非变异方法时,可以用新数组替换旧数组:
example1.items = example1.items.filter(function (item) {
return item.message.match(/Foo/)
})
下面上实例代码:
1 <div id="example"> 2 <div> 3 <button @click="concat()">concat</button> 4 <button @click="slice()">slice</button> 5 <button @click="filter()">filter</button> 6 </div> 7 <ul> 8 <li v-for="item in items"> 9 {{item.list}} 10 </li> 11 12 </ul> 13 </div> 14 <script> 15 var example = new Vue({ 16 el:"#example", 17 data:{ 18 items:[ 19 {list:5}, 20 {list:6}, 21 {list:7} 22 23 ], 24 addValue:{list:10} 25 }, 26 methods:{ 27 concat(){ 28 this.items= this.items.concat(this.addValue) 29 }, 30 slice(){ 31 this.items = this.items.slice(1) 32 }, 33 filter(){ 34 this.items = this.items.filter(function(item,index,arr) { 35 return (index > 0) 36 }) 37 } 38 39 } 40 })
以上操作并不会导致Vue丢弃现有DOM并重新渲染整个列表。Vue实现了一些智能启发式方法来最大化DOM元素重用,所以用一个含有相同元素的数组去替换原来的数组是非常高效的操作
#注意事项
1 注意事项 2 3 由于 JavaScript 的限制,Vue 不能检测以下变动的数组: 4 当你利用索引直接设置一个项时,例如:vm.items[indexOfItem] = newValue 5 当你修改数组的长度时,例如:vm.items.length = newLength 6 为了解决第一类问题,以下两种方式都可以实现和 vm.items[indexOfItem] = newValue 相同的效果,同时也将触发状态更新: 7 // Vue.set 8 Vue.set(example1.items, indexOfItem, newValue) 9 // Array.prototype.splice 10 example1.items.splice(indexOfItem, 1, newValue) 11 为了解决第二类问题,你可以使用 splice: 12 example1.items.splice(newLength)
上段文字的意思就是假如有一个数组
1 // 第一类问题如下 2 var arr = [1,2,3,4,5]; 3 arr[0] = 6; // 利用索引直接设置一个项时Vue检测不到 4 5 //第一类问题需要这样解决: 6 Vue.set(arr, 0, 6); 7 8 9 //第二类问题如下: 10 var arr = [1,2,3,4,5]; 11 arr.length = 2; // 这样Vue也是无法检测到的 12 13 //第二类方法可以用splice解决 14 arr.splice(2);
直接上代码结束这篇博客
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>注意事项</title> 6 <script src="vue.js"></script> 7 </head> 8 <body> 9 <div id="example"> 10 <div> 11 <button @click="setVal">setVal</button> 12 <button @click="setLength">setLength</button> 13 <button @click="pop">pop</button> 14 </div> 15 <ul> 16 <li v-for="item in items">{{ item }}</li> 17 </ul> 18 <p> {{ message }} </p> 19 </div> 20 <script> 21 var watchFunc = function(){ 22 example.message = "数据发生变化"; 23 setTimeout(function(){ 24 example.message = ""; 25 26 },500) 27 28 } 29 var example = new Vue({ 30 el:"#example", 31 data:{ 32 items:['Foo','Bar','BaZ',"Hello"], 33 message:"", 34 }, 35 watch:{ 36 items:watchFunc 37 }, 38 methods:{ 39 pop(){ 40 this.items.pop() 41 }, 42 setVal(){ 43 Vue.set(this.items,0,'match') 44 }, 45 setLength(){ 46 this.items.splice(2); 47 } 48 } 49 }) 50 51 </script> 52 </body> 53 </html>