This article will talk about Vue.set and this.$set in Vue, and introduce the usage and usage scenarios of Vue.set and this.$set. I hope it will be helpful to everyone!
Due to JavaScript limitations, Vue cannot detect changes in arrays and objects in data, so it will not trigger View updated. vuejs video tutorial
Vue encapsulates these JS array methods, and array updates can be detected through these methods.
In the following example, 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>
In the following example, it is necessary to add a key-value pair {test: 'newthing'} to the object
<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>
Vue cannot detect changes in the following arrays :
vm.list[0]=newValue
vm.list.length=newLength
For example
var vm = new Vue({ data: { items: ['a', 'b', 'c'] } }) vm.items[1] = 'x' // 不是响应性的 vm.items.length = 2 // 不是响应性的
You can use Vue.set or this.$set
Vue.set(target,index,newValue)
// Vue.set Vue.set(vm.items, indexOfItem, newValue)
// this.$set vm.$set(vm.items, indexOfItem, newValue)
Vue cannot Detect the addition or removal of properties. Since Vue will perform getter/setter conversion on the property when initializing the instance, the property must exist on the data object for Vue to convert it to reactive.
Give a chestnut
var vm = new Vue({ data:{ a:1 } }) // `vm.a` 是响应式的 vm.b = 2 // `vm.b` 是非响应式的
Vue.set(target,key,value)
Vue.set(vm.someObject, 'b', 2)
this.$set(this.someObject,'b',2)
Vue does not allow dynamic additionRoot levelResponsive attributes
const app = new Vue({ data: { a: 1 } // render: h => h(Suduko) }).$mount('#app1') Vue.set(app.data, 'b', 2)
Only Use the Vue.set(object, propertyName, value) method to add responsive properties to nested objects
var vm=new Vue({ el:'#test', data:{ //data中已经存在info根属性 info:{ name:'小明'; } } }); //给info添加一个性别属性 Vue.set(vm.info,'sex','男');
When When we modify the array or object in data, some operations are non-responsive. Vue cannot detect data updates, so it will not trigger view updates. At this time, you need to use Vue.set() for responsive data updates.
(Learning video sharing: vuejs tutorial, web front-end)
The above is the detailed content of A brief analysis of Vue.set and this.$set in Vue and a look at the usage scenarios!. For more information, please follow other related articles on the PHP Chinese website!