Categories
Vue Answers

How to change object in array and trigger reactivity with Vue.js?

Spread the love

Sometimes, we want to change object in array and trigger reactivity with Vue.js

In this article, we’ll look at how to change object in array and trigger reactivity with Vue.js.

How to change object in array and trigger reactivity with Vue.js?

To change object in array and trigger reactivity with Vue.js, we can use the this.$set method.

For instance, we write

<script>
//...
export default {
  //...
  methods: {
    update(index) {
      this.$set(this.arr, index, { ...this.arr[index], foo: "bar" });
    },
  },
  //...
};
</script>

to call this.$set with the this.arr array we want to update, the index of the item we want to update, and the object we want to update the object at the index to.

Calling this.$set will trigger Vue.js to notice the changes in the object in the array that’s changed and re-render the component.

Conclusion

To change object in array and trigger reactivity with Vue.js, we can use the this.$set method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *