vue set for setting reactive properties in vuejs
The vue set global api method in vuejs can be used to set a property of a reactive object. In other words it is a way to add a property to an object in the data of a Vue constructor instance, and have the view update when a change happens to that property. Many times this should happen automatically, but in some cases it might not when it comes to nested objects.
The thing about this is that many frameworks have a method like this, because sometimes you can not just simply add a property to an object, or doing so is not a good idea at times. Sometimes some additional things need to happen on top of just simply setting a properly of an object, such as setting up something to watch that property of changes, and then do something when a change occurs.
1 - vue set example
For a quick example of vue set, I put something together that makes use of a property in the data object but only if it is there. So in the example there is a root property in the data option object that is also an object, this is impotent because there is no way to add root properties to the data object with vue set. However vue set can be used to add properties to an object that is nested in the data object.
When I use the vue set method to set the value of the mess property of the u object in the data object the message bar is displayed as expected. If I where to just add the property directly the message will not display, because it is not reactive. This is the whole reason why there is the vue set method in the global api of vuejs, it is a way to add properties to a reactive object after the fact.
1.1 - Using force update as an alternative to making properties reactive
Another option is to use the vue force update method to force the vue to render again. This is a way to manually render the view again rather than have it update each time a value chances. With some projects I might want to have things work that way where the view does not always update each time I change a value in the state, but for the most part I would want that to happen.
In any case those are the two options make the property reactive if it is not to begin with, or use the force update method now and then where needed to render the view again when doing so is called for.
2 - A word on setters
3 - Conclusion
So that is it for now when it comes to the vue set method, there is only so much to write about it for now at least anyway. When I get around to running into problems where I need to use the vue set method I am sure I will get around to expanding this post more with additional examples.