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

I carefully read and re-read Vue docs "Reactivity in depth" and the API for vm. $ set and Vue.set , but it’s still hard for me to determine which time to use. It is important for me to distinguish between the two, because in my current Laravel project we set many properties on objects dynamically.

The difference in the documents seems to be between the language in which vm. $ set is "For an instance of Vue", and Vue.set is "For simple 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 instance method $ set (path, value):

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

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

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

Finally, I was wondering if the third β€œoption” can be made higher (which consists of adding several properties at a time) can be used as an equivalent replacement for one of the two options above (adding instead only 1 property of several)?

Sometimes you may need to assign a number of properties to an existing object, for example, using Object.assign () or _.extend (). However, new properties added to the object will not cause changes. In such cases, create a new 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 }) 
+20
source share
2 answers

Here's the release note that came up with the introduction of Vue.set:

Vue no longer extends Object.prototype with the $ set and $ delete methods. This causes problems with libraries that rely on these properties under certain validation conditions (e.g. minimongo in Meteor). Instead of an 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 for all objects - now it is available only on the viewing model itself. Vue.set therefore used in cases where you have a reference to a reactive object, but do not have a reference to the view model to which it belongs.

+21
source

found that adding more than one attribute to an object with .$set() only works well once, maybe Vue first put these added attributes into a sequence, and then applied these sequences to the receiver and installer; eg

 Vue.set(this.b,'first','first'); this.b.second = 'second'; this.b.third = 'third'; this.b.fourth = 'fourth'; 

'second','third','fourth' also react as 'first'

0
source

Source: https://habr.com/ru/post/1247281/


All Articles