In the development process, we often encounter a situation where we add a new property to an object or array declared or already assigned in vue data. If the value of the property is updated, the view is not updated.

If you add new attributes to an instance after it is created, it does not trigger view updates, according to the official documentation. Restricted by modern JavaScript (and deprecated Object.Observe), Vue cannot detect additions or deletions of Object attributes. Since Vue performs getter/setter conversion procedures on the property when it initializes the instance, the property must exist on the data object for Vue to convert it so that it can be a response.

Vue does not allow you to dynamically add root-level reactive properties to instances that have already been created. Set (vm.obj, ‘e’, 0) you can also use the vm.$set instance method, which is also an alias for the global Vue. Set method: this.$set(this.obj, ‘e’, 2)

So why does this happen? To start with how Vue implements data binding (Object.defineProperty), suppose we simplify the Vue data binding to the following code:

The < div > < h3 > display name: < span id = "name" > < / span > < / h3 > < p > enter name: <input type="text" oninput="inputHandler('name', this.value)" /></p> <h3> Display phone number: <span id="phone"></span></h3> <p> Input phone number: <input type="text" oninput="inputHandler('phone', This.value)" /></p> </div> <script type="text/javascript"> ---- var obj = {name: DefineProperty for(let key in obj) {let val = obj[key]; Object.defineProperty(obj, key, { enumerable: true, configurable: true, get() { return val; }, set(newValue) { if(val === newValue) { return; } document.getElementById(key).innerText = newValue; val = newValue; } }) } var inputHandler = function(key, value) { obj[key] = value; } </script>Copy the code

Is there a way to automatically bind new attributes? The answer is, of course, there is, that is, the upcoming Vue3.0 also uses ES6’s new API-proxy, with the new Proxy changed some code as follows:

The < div > < h3 > display name: < span id = "name" > < / span > < / h3 > < p > enter name: <input type="text" oninput="inputHandler('name', this.value)" /></p> <h3> Display phone number: <span id="phone"></span></h3> <p> Input phone number: <input type="text" oninput="inputHandler('phone', This.value)" /></p> </div> <script type="text/javascript"> ---- var obj = {name: null } obj = new Proxy(obj, { get: function(target, prop) { console.log('proxy get:', target, prop); }, set: function(target, prop, value) { document.getElementById(prop).innerText = value; target[prop] = value; console.log('proxy:', target, prop, value); } }) var inputHandler = function(key, value) { obj[key] = value; } </script>Copy the code

$set = $set = $set = $set = $set Look forward to the arrival of Vue3.0.