Vue 包含一組觀察數組的變異方法,變異方法 (mutation method),顧名思義,會改變被這些方法調用的原始數組
所以它們也將會觸發視圖更新。這些方法如下:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
你打開控制台,然后用前面例子的 items
數組調用變異方法:example1.items.push({ message: 'Baz' })
。
這些方法是不是很熟悉,這些都是原生js數組的方法,會專門寫篇博客回顧這些方法這里就看實例吧
1 <div id="example"> 2 <div> 3 <button @click="push()">push</button> 4 <button @click="pop()">pop</button> 5 <button @click="shift()">shift</button> 6 <button @click="unshift()">unshift</button> 7 <button @click="splice()">splice</button> 8 <button @click="sort()">sort</button> 9 <button @click="reverse()">reverse</button> 10 </div> 11 <ul> 12 <li v-for="item in items"> 13 {{item.message}} 14 </li> 15 16 </ul> 17 </div> 18 <script> 19 var example = new Vue({ 20 el:"#example", 21 data:{ 22 23 items:[ 24 {message:5}, 25 {message:2}, 26 {message:7} 27 ], 28 addValue:{message:5}, 29 addSplice:{message:'Thank'}, 30 }, 31 methods:{ 32 push(){ 33 this.items.push(this.addValue) //末尾添加 34 }, 35 pop(){ 36 this.items.pop() // 末尾刪除 37 }, 38 shift(){ 39 this.items.shift() // 開頭刪除 40 }, 41 unshift(){ 42 this.items.unshift(this.addValue) //開頭添加 43 }, 44 splice(){ 45 this.items.splice(1,0,this.addSplice); // 從第二個位置添加一個Thank 46 }, 47 sort(){ 48 this.items.sort(function(a, b){ 49 return a.message < b.message; // 比較大小 50 }); 51 }, 52 reverse(){ 53 this.items.reverse() // 反轉數組 54 }, 55 56 } 57 58 }) 59 </script>
變異方法
push() 接收任意數量的參數,把它們逐個添加到數組末尾,並返回修改后數組的長度
pop() 從數組末尾移除最后一項,減少數組的length值,然后返回移除的項
shift() 移除數組中的第一個項並返回該項,同時數組的長度減1
unshift() 在數組前端添加任意個項並返回新數組長度
splice() 刪除原數組的一部分成員,並可以在被刪除的位置添加入新的數組成員
sort() 調用每個數組項的toString()方法,然后比較得到的字符串排序,返回經過排序之后的數組
reverse() 用於反轉數組的順序,返回經過排序之后的數組