vue修改數(shù)據(jù)頁面無效的解決方案
vue修改數(shù)據(jù)頁面無效
項目開發(fā)的過程中,經(jīng)常會遇到這種情況:為data中的某一個對象添加一個屬性。
如下案例
<!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對象添加屬性 console.log(this.student); } } }) </script> </body> </html>
原因是由于受JavaScript的限制,vue.js不能監(jiān)聽對象屬性的添加和刪除,因為在vue組件初始化的過程中,會調(diào)用getter和setter方法,所以該屬性必須是存在在data中,視圖層才會響應(yīng)該數(shù)據(jù)的變化,針對這個問題
有兩種解決方案
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ù)后頁面不刷新的問題
今天遇到的,通過v-if控制標簽切換效果,出現(xiàn)沒任何反應(yīng)的情況。檢測數(shù)據(jù)正常,只是頁面沒有渲染。
查了很多資料因為數(shù)據(jù)層次太多,render函數(shù)沒有自動更新,需手動強制刷新。
通過
this.$forceUpdate();
強制刷新即可
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vant遇到van-sidebar數(shù)據(jù)超出不能滑動的問題
這篇文章主要介紹了vant遇到van-sidebar數(shù)據(jù)超出不能滑動的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04Vue 讀取HTMLCollection列表的length為0問題
這篇文章主要介紹了Vue 讀取HTMLCollection列表的length為0問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06