Vue心得笔记(1) -- array的响应

版本: 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有响应哩!
http://img2.58codes.com/2024/emoticon09.gif

怎解?
简单,动一下本尊就行:

      methods: {        myClick() {          this.myArray[1] += 100          //--------------          let tmp = this.myArray          this.myArray = [];          this.myArray = tmp;          //--------------          console.log(this.myArray, 'array内容改变了,画面响应了')        },      }

好像有点逊...
http://img2.58codes.com/2024/emoticon28.gif
不然就抓个有响应的伴下水,看你要不要渲染
...暴力http://img2.58codes.com/2024/emoticon05.gif

      ...      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真的比较有感觉...http://img2.58codes.com/2024/emoticon51.gif

网路上有更多解法:

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()。

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章