Zhou TK
Zhou TK

Reputation: 91

How v-model make a property of object reactive?

Link to my project: https://codesandbox.io/s/v-model-3j96f

As of my link above, the is a file named HelloWorld.vue inside the "components" folder: inputvalue.bbbb is a reactive data which is defined in data option, but

It's weird that inputvalue.cccc will become reactive after input with the v-model, but inputvalue.cccc will not reactive with @input.

In this question (Vue.js bind object properties), the first situation should not be possible.

Upvotes: 5

Views: 5791

Answers (1)

skirtle
skirtle

Reputation: 29092

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://v2.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.

Upvotes: 4

Related Questions