Home > Net >  Add new key for empty data object not working in Vuejs
Add new key for empty data object not working in Vuejs

Time:06-09

I have question related to data of Vue.

I created data with an empty object.

data(){
 return {
    myObj: {}
 }
}

and function like this:

methods: {
  changeMyObj() {
    this.myObj.newKey = 'aaaa';
  }
}

Then I show it on template by click

  <a @click="changeMyObj">Click change</a>
     {{myObj.newKey}}

With this click, the nested key is not rendered on template. How can I resolve this issue?

Note: I do not meet this issue with Vuex or state of React.

CodePudding user response:

This happens because of vue.js reactivity. In fact, here you are modifying a value that was not declared when the component mounted and Vue cannot track the changes.


You can update values by using the Vue.set method which allows Vue to track the data.

Vue.set(this.myObj, "myKey", "Hello world")

You can also make a deep copy of the object instead of just adding the key.

This can be done using the spread operator.

For example

this.myObj = {...this.myObj, myKey: "Hello world"}

Here is a small example using the two versions

new Vue({
  el: "#app",
  data: () => ({
    myObj: {}
  }),
  
  methods: {  
    addKey(){
      this.myObj = {...this.myObj, myKey: "Hello world foo"}
    },
    addKey2(){
      Vue.set(this.myObj, "myKey", "Hello world bar")
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ myObj.myKey }}
  <button @click="addKey">Add key</button>
  <button @click="addKey2">Add key 2</button>
</div>

CodePudding user response:

I found the solution for this.

this.myObj = {...this.myObj, newKey:'aaaa'}

I do not think it is solution while it has no difference with:

this.myObj['newKey'] = 'aaaa';
or
this.myObj.newKey = 'aaaa';

If someone can explain why please let me know. Thanks

CodePudding user response:

Correct way to assign a new property in an existing object is Vue.set(this.myObj, 'newKey', 'aaaa') to make it reactive instead of this.myObj.newKey = 'aaaa'

Demo :

new Vue({
  el: '#app',
  data: {
    myObj: {}
  },
  methods: {
    changeMyObj() {
      Vue.set(this.myObj, 'newKey', 'aaaa')
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="changeMyObj">Click change</button>
    {{ myObj.newKey }}
</div>

CodePudding user response:

i think you need to assign a variable to an object like this:

this.myObj['newKey'] = 'aaaa';

  • Related