preface

When we pass a data to the Vue instance data attribute to complete the view update, we find that the data is not updated after some operation. The console print discovery data is just JavaScript normal object data.

The reason is that Vue must convert JavaScript normal object data into property object data with getters/setters in order to complete the view response. Vue captures the data when the call setter is called to complete the response component update. Vue.js – Deep response principle

To detect changes

The following ways to allow a view response to be created are:

  • Add the initial attribute value in the Vue instance data as the response node
  • The response node is dynamically added using the $set method

The instance

First, we prepare two sets of data, jsData and vueData.

const jsData = {
  ja: "Zhang".jb: "Bill"
}
export default {
  data() {
    return {
      vueData: {
        va: "Zhang".vb: "Bill"
      }
    }
  },
  mounted() {
    console.log(jsData, this.vueData);
  },
  // ...
}
Copy the code

JsData is not created in vUE instance and does not have getter/setter. VueData has getter/setter by creating the initial property value in vue instance data.

No updates allowed

Examples of views that do not detect changes are as follows:

export default {
  // ...
  mounted() {
    console.log(jsData, this.vueData);
    this.notAllow()
  },
  methods: {
    notAllow() {
      // demo 1
      this.vueData.newKeyA = "keyA";
      console.log(this.vueData);

      // demo 2
      // Object.assign(this.vueData, { newKeyA: "keyA" });
      // console.log(this.vueData);

      // demo 3
      // this.vueData = Object.assign(this.vueData, { newKeyA: "keyA" });
      // console.log(this.vueData);}}}Copy the code

The problem in each of these codes is that inserting data into the same reference type causes the data object itself to remain unchanged, which means that Vue cannot check that the data memory is pointing to the change, which results in inserting only getter/setter properties.

Running result:

Allows you to update

export default {
  mounted() {
    console.log(jsData, this.vueData);
    this.allow()
  },
  methods: {
    allow() {
      // demo 1
      this.vueData = { ... this.vueData,newKeyA: "keyA"
      }
      console.log(this.vueData);

      // demo 2
      // this.$set(this.vueData, "newKeyA", "keyA");
      // console.log(this.vueData);}}}Copy the code

The above demo1 way is to replace a memory point to complete the data change. Demo2 is the $set method provided by the Vue instance, which is supplemented by adding a getter/setter property without changing the inner point.

Running result:

example

See GitHub for a demo of this article

* Copyright notice: This article is an original article, shall not be reproduced without permission.