0

I know that if I want to add a property to a data object, I use Vue.set(). I did this in my created() lifecycle method ... a new field will be added to the myObject. But what about if I wanted to make an api call and completely replace the existing data object of myObject? Can I do what I am doing in updateMore() method or is there another way to handle this?

data() {
   return {
      myObject: {}
   }
},
async created() {
     let apiData = await axios.get('http://myurl.com');
     this.$set(this.myObject, 'name', apiData.name);
},
methods: {
   updateMore() {
       let moreAPIData = await axios.get('http://myurl.com');

       // will this completely override `myObject` with `moreAPIData` and still be reactive? 
       this.myObject = moreAPIData;
   }
}
1
  • According to this Vue Forum post async doesn't work with 'created()'. Commented Mar 2, 2021 at 4:55

1 Answer 1

1

TL;DR:

This assignment of a new object is fine. Vue reactivity issues occurs when you add a new key to an object, because the object is the same, what changed was its content. Javascript compares objects by its address, so if I do

new MyClass() === new MyClass()

it returns false, because, even if they have the same content, they have different addresses.

To conclude, when you set a whole new object, Vue is able to track the difference, but when you change the content of one key, it can't.

Full boring text

You can read the whole documentation about reactivity in Vue here

Sign up to request clarification or add additional context in comments.

2 Comments

Would I be able to do this this.myObject = {...moreAPIData, ...this.myObject} ...use the spread operator to set myObject to the myObject properties and moreAPIData combined?.... or is that technically considered adding a new key?
Notice that 'this.myObject' is a whole new object now, so reactivity ;) . It is also worth noting that depending on the depth of the object, spread operator might not be enough, requiring a 'deep clone' to remove the reference to nested objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.