Why I can't bind the object properties in Vue? The object addr
is not reactive immediately, but test
is reactive, how come? In this case, how should I bind it?
HTML
<div id="app"> <input type="text" id="contactNum" v-model="addr.contactNum" name="contactNum"> <input type="text" id="test" v-model="test" name="test"> <br/> {{addr}}<br/> {{addr.contactNum}}<br/> {{test}} </div>
Javascript
var vm = new Vue({ el: '#app', data: { addr: {}, test: "" } });
Jsfiddle
During initialisation Vue sets up getters and setters for every known property. Since contactNum
isn't initially set up, Vue doesn't know about that property and can not update it properly. This can be easly fixed by adding contactNum
to your addr
object.
var vm = new Vue({ el: '#app', data: { addr: { contactNum: "" // <-- this one }, test: "" } });
The above is called reactivity in Vue. Since Vue doesn't support adding properties dynamically to its reactivity system, we may need some kind of workaround. A possible solution is provided by the API. In case of dynamically added properties we can use Vue.set(vm.someObject, 'b', 2)
.
Doing so the markup would need to get some update. Instead of using v-model
it'd be better to use an event listener like @input
. In this case our markup could look like this.
<input type="text" id="contactNum" @input="update(addr, 'contactNum', $event)" name="contactNum">
So basically the function will get triggered every time the input elements value changes. Obviously doing so will also require some adjustments on the JS part.
var vm = new Vue({ el: '#app', data: { addr: {}, test: "" }, methods: { update: function(obj, prop, event) { Vue.set(obj, prop, event.target.value); } } });
Since Vue triggers Vue.set()
on any reactive element, we simply call it on our own because Vue doesn't recognizes a dynamically added property as a reactive one. Of course, this is only one possible solution and there may be lots of other workarounds. A fully working example can be seen here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With