Vue cannot detect the addition or deletion of object attributes:

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <p>{{obj.a}}</p>
</div>
<script>
  var vm = new Vue({
    el: '#app',
    data: {
      obj: {},
    },
    mounted() {
      this.obj.a = 1111
    }
  })
</script>
</body>
</html>Copy the code

Run it and the browser doesn’t render anything, right

Because obj properties are dynamically added by me!!



Again, due to JavaScript limitations, vue cannot detect the addition or deletion of object attributes:

So to dynamically add the attributes of the object and update the page to you can use the following method:

this.$set(this.obj,'a'Object.obj = object.assign ({}, this.obj,{a:1})Copy the code

Second,Array update detection

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <p v-for="item in arr"  :key="item.id">{{item}}</p>
</div>
<script>
  var vm = new Vue({
    el: '#app',
    data: {
      arr: [],
    },
    mounted() {
      this.arr.push(1)
    }
  })
</script>
</body>
</html>Copy the code

Why do we push an array and it shows up on the page? I hadn’t thought about that before!! I didn’t know until I typed VM enter into the Console panel and saw the following:



These Vue contain a set of observation array variation methods!! Not the original push method!!

I tried to console. The log (this. Arr. Push)

The printout reads:

function mutator() {
  var args = [], len = arguments.length;
  while (len--) args[len] = arguments[len];
  var result = original.apply(this, args);
  var ob = this.__ob__;
  var inserted;
  switch (method) {
    case 'push':
    case 'unshift':
      inserted = args;
      break
    case 'splice':
      inserted = args.slice(2);
      break
  }
  if (inserted) {
    ob.observeArray(inserted);
  } 
    // notify change 
    ob.dep.notify();
     return result 
}Copy the code

Ob.dep.notify () notifies you to update the page when the push method is wrapped by vUE!



# Precautions

Due to JavaScript limitations, Vue cannot detect the following altered arrays:

  1. When you set an item directly using an index, for example:vm.items[indexOfItem] = newValue
  2. When you modify the length of an array, for example:vm.items.length = newLength

To solve the first type of problem, either of the following methods can achieve the same effect as vm.items[indexOfItem] = newValue, and also trigger a status update:

// Vue.set
Vue.set(example1.items, indexOfItem, newValue)
Copy the code
// Array.prototype.splice
example1.items.splice(indexOfItem, 1, newValue)
Copy the code

To solve the second type of problem, you can use Splice:

example1.items.splice(newLength)Copy the code