版本: Vue.js v2.6.10
使用方式:
<html><head> <script src="https://unpkg.com/vue/dist/vue.js"></script></head><body> <!-- your HTML code with Vue--></body></html>
你发现了吗? Vue对 array成员内容的异动是无响应的:
<div id="app"> array内容 -- {{ myArray }} <br> <input type="button" @click="myClick()">Click and view console</input> </div> <script> var vm = new Vue({ el: '#app', data: { myArray: [1, 2, 3, 4, 5] }, methods: { myClick() { this.myArray[1] += 100 console.log(this.myArray, 'array内容改变了,但画面没有响应') }, } }); </script>
加个watch观察一下...确定静悄悄:
watch: { myArray: { handler: function (vnew, vold) { console.log(vnew, 'watch it!'); }, deep: true //drill down sensor } },
开始解释了...
这是JS的特性嘛~array参照没变,还是原来那个...
不然改成 object试看看:
... object内容 -- {{ myObj }} ... data: { myObj: { id: 10, age: 20, year: 150, qty: 0 } }, //.... methods: { myClick() { this.myObj.qty += 100 console.log(this.myObj, 'object内容改变了,响应正常') }, }
人家对 object有响应哩!
怎解?
简单,动一下本尊就行:
methods: { myClick() { this.myArray[1] += 100 //-------------- let tmp = this.myArray this.myArray = []; this.myArray = tmp; //-------------- console.log(this.myArray, 'array内容改变了,画面响应了') }, }
好像有点逊...
不然就抓个有响应的伴下水,看你要不要渲染
...暴力
... array内容 -- {{ myArray }} {{ cnt }} <!--(3)--> ... data: { myArray: [1, 2, 3, 4, 5], cnt: 0 //(1) }, //.... methods: { myClick() { this.cnt++ //(2) this.myArray[1] += 100 console.log(this.myArray, 'array内容改变了,画面响应了') }, }
原来这也是我到今天才发现 array不会响应的原因 (因为跟着其它的一起渲染了)
还有这个原因
data: { myArray: [1, 2, 3, 4, {id: 5} ], //(1) }, //.... methods: { myClick() { this.myArray[4].id += 100 //(2) console.log(this.myArray, 'array内容改变了,画面响应了') }, }
Vue对 Object真的比较有感觉...
网路上有更多解法:
https://pjchender.blogspot.com/2017/05/vue-vue-reactivity.html
解法整理:
改变 array参照随附其它会响应的 data一起渲染修改 array成员内容时改用 this.$set这些在 array上的 function能促使 Vue重新渲染画面:push()、pop()、shift()、unshift()、splice()、sort()、reverse()。