Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

javascript - What is the difference between vm.$set and Vue.set?

I have carefully read and re-read the Vue docs "Reactivity in Depth" and the API for vm.$set and Vue.set but I am still having a difficult time determining when to use which. It is important for me to be able to distinguish between the two because in my current Laravel project, we are setting a lot of properties on objects dynamically.

The distinction in the docs seems to be between the language that vm.$set is "For Vue instance" while Vue.set is "For plain data objects" and that Vue.set is global:

However, there are ways to add a property and make it reactive after an instance has been created.

For Vue instances, you can use the $set(path, value) instance method:

vm.$set('b', 2)
// `vm.b` and `data.b` are now reactive

For plain data objects, you can use the global Vue.set(object, key, value) method:

Vue.set(data, 'c', 3)
// `vm.c` and `data.c` are now reactive

Finally, I was wondering if the 3rd "option" of doing the above (which is for adding multiple properties at one time) could be used as an equivalent substitute for either of the 2 options above (by adding just 1 property instead of multiple)?

Sometimes you may want to assign a number of properties on to an existing object, for example using Object.assign() or _.extend(). However, new properties added to the object will not trigger changes. In such cases, create a fresh object with properties from both the original object and the mixin object:

// instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
question from:https://stackoverflow.com/questions/36671106/what-is-the-difference-between-vm-set-and-vue-set

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the release note that went with the introduction of Vue.set:

Vue no longer extends Object.prototype with $set and $delete methods. This has been causing issues with libraries that rely on these properties in certain condition checks (e.g. minimongo in Meteor). Instead of object.$set(key, value) and object.$delete(key), use the new global methods Vue.set(object, key, value) and Vue.delete(object, key).

So, .$set used to be available on all objects - it is now only available on a View Model itself. Vue.set is therefore used in those cases now when you have a reference to a reactive object but do not have a reference to the View Model it belongs to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...