vue修改數(shù)據(jù)頁(yè)面無(wú)效的解決方案
vue修改數(shù)據(jù)頁(yè)面無(wú)效
項(xiàng)目開(kāi)發(fā)的過(guò)程中,經(jīng)常會(huì)遇到這種情況:為data中的某一個(gè)對(duì)象添加一個(gè)屬性。
如下案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <button @click="addAttribute()">添加屬性方法</button> <p>student屬性顯示在下面</p> <ul> <li v-for="item in student">{{item}}</li> </ul> </div> <script src="./js/vue.js"></script> <script> new Vue({ el: '#app', data: { student: { name: 'zdx' } }, methods: { addAttribute() { this.student.age = 18; //為student對(duì)象添加屬性 console.log(this.student); } } }) </script> </body> </html>
原因是由于受JavaScript的限制,vue.js不能監(jiān)聽(tīng)對(duì)象屬性的添加和刪除,因?yàn)樵趘ue組件初始化的過(guò)程中,會(huì)調(diào)用getter和setter方法,所以該屬性必須是存在在data中,視圖層才會(huì)響應(yīng)該數(shù)據(jù)的變化,針對(duì)這個(gè)問(wèn)題
有兩種解決方案
1.this.$set(obj, key, value) 或 vue.set(obj, key, value)
methods: { addAttribute() { // this.student.age = 18; this.$set(this.student, 'age', 18); console.log(this.student); } }
2.Object.assign(target, sources)
methods: { addAttribute() { // this.student.age = 18; // this.$set(this.student, 'age', 18); this.student.age = 18; this.student = Object.assign({}, this.student); console.log(this.student); } }
更改數(shù)據(jù)后頁(yè)面不刷新的問(wèn)題
今天遇到的,通過(guò)v-if控制標(biāo)簽切換效果,出現(xiàn)沒(méi)任何反應(yīng)的情況。檢測(cè)數(shù)據(jù)正常,只是頁(yè)面沒(méi)有渲染。
查了很多資料因?yàn)閿?shù)據(jù)層次太多,render函數(shù)沒(méi)有自動(dòng)更新,需手動(dòng)強(qiáng)制刷新。
通過(guò)
this.$forceUpdate();
強(qiáng)制刷新即可
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue通信方式EventBus的實(shí)現(xiàn)代碼詳解
這篇文章主要介紹了vue通信方法EventBus的實(shí)現(xiàn)代碼,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06vant遇到van-sidebar數(shù)據(jù)超出不能滑動(dòng)的問(wèn)題
這篇文章主要介紹了vant遇到van-sidebar數(shù)據(jù)超出不能滑動(dòng)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04vue不用window的方式如何刷新當(dāng)前頁(yè)面
這篇文章主要介紹了vue不用window的方式如何刷新當(dāng)前頁(yè)面,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11基于vue實(shí)現(xiàn)swipe分頁(yè)組件實(shí)例
本篇文章主要介紹了基于vue實(shí)現(xiàn)swipe分頁(yè)組件實(shí)例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05Vue 讀取HTMLCollection列表的length為0問(wèn)題
這篇文章主要介紹了Vue 讀取HTMLCollection列表的length為0問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06