Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js bind object properties

Tags:

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

like image 331
Sam YC Avatar asked Oct 25 '17 06:10

Sam YC


1 Answers

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.

like image 136
Aer0 Avatar answered Sep 27 '22 23:09

Aer0