Changing object data triggers view updates

Vue is bidirectional data binding (data updates, view updates; Data automatically updates after an attempt to update). However, after performing some operations, you find that the data is changed but the view is not updated

<! DOCTYPEhtml>
<html>

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <h1 style="display: none;">{{name}}</h1>
    <h2>{{obj}}</h2>
    <h3>{{arr}}</h3>
  </div>
  <script src=".. /node_modules/vue/dist/vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app'.data: {
        name: 'test'.test: 1.obj: {
          a: 123
        },
        arr: [1.2.3.4]}}); vm.obj.b =100;  // Attributes are added, but the obj in the page does not change
     console.log(vm.obj);

    // The view was not updated because vue hijacked the obj, obj.a, and name attributes originally set, but did not hijack the obj.b attribute

  </script>
</body>
</html>
Copy the code

The solution

  • Method 1: Change the address of the entire OBJ

Because OBj is hijacked, changing the entire address of OBj triggers a view update

// The newly added attribute will also be hijacked, and later changes to its value will trigger view updates
    vm.obj = Object.assign({
      b: 100
    }, vm.obj);
    // object. assign(obj1,obj2) : merge obj2 to obj1 and return the address of obj1
Copy the code
  • Method 2: Use other data hijacked by VUE (folk remedies, not recommended)

View updates are triggered by changes to other hijacked data, ostensibly due to the addition of new data, but in fact the update of the view is not directly related to the addition of new data.

 // A newly added attribute is not hijacked, and changing its value later does not trigger a view update
    vm.obj.b = 104;
    vm.name = 1; // It is important to note that the name value must be used in the page, otherwise it is useless (if you do not need to display it, use display:' None 'to hide it). If you use test, it is invalid because the value */ is not used in the page
   // vm.obj.b = 100;
   // vm.test = 13;
Copy the code
  • $set(target object, new attribute name, attribute value)
   // The newly added attribute is hijacked, and changing its value later triggers a view update
    vm.$set(vm.obj, 'b'.100);
    
     /* Data is hijacked by vue; /* Data is hijacked by vue; For example, vm.name. 2. 

{{name}}

*/
Copy the code

Change the array trigger view update method

// In the case of arrays, modifying arrays by index or length does not trigger view updates
 /* vm.arr.length = 6; vm.arr[3] = 34; * /

Push pop Unshift Shift Reverse splice sort can be used to trigger view updates without changing the address of the entire array
    vm.arr.push(100);
    vm.arr.splice(2.1.30); // Replace the element with subscript 2 with 30
Copy the code