Home > Blockchain >  Why data changed after mounted in vue 2?
Why data changed after mounted in vue 2?

Time:04-15

<template>
  <div>
    {{testData.first}}
    <!-- The screen shows the value set by mounted. -->
  </div>
</template>
<javascript>
export default {
  data(){
    return {
      testData: {}
    }
  },
  mounted(){
    this.testData.first = 'hello';
  }
}
</javascript>

I understand that when mounted is called in the life cycle of 'vue', data is already defined. I do not define the properties of testData. I initially did not set a property of the testData when mounted is called, so I think must be visible screen at the empty value. Of course, I've already known testData isn't reactivity data. Please explain why this phenomenon occurs. Maybe I didn't understand Vue well.

CodePudding user response:

Of course, I've already known testData isn't reactivity data.

testData is reactive, because it's what you declared. But testData.first is not, because it's NOT what you declared. So you tell Vue testData is a reactive object, but you changed a non-existent property, which is a totally different story.

Therefore, if you declare it as a reactive object, you have to give it an object, totally makes sense. Otherwise, if you want to give it a property, you have to tell Vue. This can be done with the aid of Vue $set.

const app = new Vue({
  el: "#app",
  data() {
    return {
      testData: {}
    }
  },
  template: `<div>{{testData.first}}</div>`,
  mounted() {
    this.testData = {
      'first': 'hello'
    }; 
    //this.$set(this.testData, 'first', 'hello'); //either will work
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
</div>

It was the inconvenience of using the ancient VueJS 2. VueJS 3 has removed $set (doc) and worked around this. So I have a high expectation that your code will work well on Vue 3

  • Related