本篇文章帶大家聊聊Vue中的Vue.set和this.$set,介紹一下Vue.set和this.$set用法與使用場景,希望對大家有所幫助!
一、為什么有Vue.set
由于JavaScript的限制,Vue無法檢測到data中數(shù)組和對象的變化,因此也不會觸發(fā)視圖更新。vuejs視頻教程
二、解決方法
數(shù)組
1.使用Vue提供的變異方法
Vue對這些JS數(shù)組方法進(jìn)行了封裝,通過這些方法是可以檢測到數(shù)組更新的。
2.將原數(shù)組整個(gè)替換
如下例中,是要實(shí)現(xiàn)vm.items[1] = 'excess'
<body> <div id="app"> <ul> <li v-for="(item, index) in items"> {{ index }} : {{ item }} </li> </ul> </div> <script> let vm = new Vue({ el: '#app', data: { items: ['a', 'b', 'c'] }, created() { this.items = ['a', 'test', 'c'] } }) </script> </body>
3.使用Vue.set(見后文)
對象
1.將原對象整個(gè)替換
如下例中,是要實(shí)現(xiàn)給object新增一個(gè)鍵值對{test: 'newthing'}
<body> <div id="app"> <ul> <li v-for="(value, name) in object"> {{ name }} : {{ value }} </li> </ul> </div> <script> let vm = new Vue({ el: '#app', data: { object: { title: 'How to do lists in Vue', author: 'Jane Doe', publishedAt: '2016-04-10' } }, created() { this.object = { title: 'How to do lists in Vue', author: 'Jane Doe', publishedAt: '2016-04-10', test: 'newthing' } } }) </script> </body>
2.使用Vue.set(見后文)
三、Vue.set
對于數(shù)組
Vue不能檢測以下數(shù)組的變動:
- 利用索引值直接設(shè)置一個(gè)數(shù)組項(xiàng)時(shí),例如
vm.list[0]=newValue
- 修改數(shù)組長度時(shí),例如
vm.list.length=newLength
舉個(gè)栗子
var vm = new Vue({ data: { items: ['a', 'b', 'c'] } }) vm.items[1] = 'x' // 不是響應(yīng)性的 vm.items.length = 2 // 不是響應(yīng)性的
這時(shí)可以使用Vue.set或者this.$set
使用方法
Vue.set(target,index,newValue)
// Vue.set Vue.set(vm.items, indexOfItem, newValue)
// this.$set vm.$set(vm.items, indexOfItem, newValue)
對于對象
Vue 無法檢測 property 的添加或移除。由于 Vue 會在初始化實(shí)例時(shí)對 property 執(zhí)行 getter/setter 轉(zhuǎn)化,所以 property 必須在 data 對象上存在才能讓 Vue 將它轉(zhuǎn)換為響應(yīng)式的。
舉個(gè)栗子
var vm = new Vue({ data:{ a:1 } }) // `vm.a` 是響應(yīng)式的 vm.b = 2 // `vm.b` 是非響應(yīng)式的
使用方法
Vue.set(target,key,value)
Vue.set(vm.someObject, 'b', 2)
this.$set(this.someObject,'b',2)
注意
Vue不允許動態(tài)添加根級響應(yīng)式屬性
const app = new Vue({ data: { a: 1 } // render: h => h(Suduko) }).$mount('#app1') Vue.set(app.data, 'b', 2)
只可以使用 Vue.set(object, propertyName, value) 方法向嵌套對象添加響應(yīng)式屬性
var vm=new Vue({ el:'#test', data:{ //data中已經(jīng)存在info根屬性 info:{ name:'小明'; } } }); //給info添加一個(gè)性別屬性 Vue.set(vm.info,'sex','男');
四、使用場景
當(dāng)我們對data中的數(shù)組或?qū)ο筮M(jìn)行修改時(shí),有些操作方式是非響應(yīng)式的,Vue檢測不到數(shù)據(jù)更新,因此也不會觸發(fā)視圖更新。此時(shí)需要使用Vue.set()進(jìn)行響應(yīng)式的數(shù)據(jù)更新。
(學(xué)習(xí)視頻分享:vuejs教程、web前端)