How v-model make a property of object reactive? How v-model make a property of object reactive? vue.js vue.js

How v-model make a property of object reactive?


Using v-model will automatically use $set to set the values on nested properties. This ensures this it works with array indices, as well as working for object properties that don't exist, as per your example.

If you're unfamiliar with $set it is documented here:

https://vuejs.org/v2/api/#vm-set

The code for this part of v-model in Vue is here:

https://github.com/vuejs/vue/blob/399b53661b167e678e1c740ce788ff6699096734/src/compiler/directives/model.js#L44

In your example there are two inputs that use cccc. As you noticed, if you edit the input that uses v-model then everything works fine. However, if you use the :value/@input input first then it doesn't work, even if you subsequently use the v-model input. The behaviour is, somewhat oddly, determined by which of those two inputs you edit first.

The reason for that can be seen in the code for $set:

https://github.com/vuejs/vue/blob/399b53661b167e678e1c740ce788ff6699096734/src/core/observer/index.js#L212

The problem is that $set will only add a reactive property if the property doesn't already exist. So if you use the :value/@input input first it will create a non-reactive cccc property and once that is created it can't be made reactive, even if you use $set. It would have to be removed using delete before it could be re-added reactively.