Blog>
Snippets

Updating Arrays and Objects with Vue.set for VDOM Reactivity

Demonstrate how to correctly update arrays or objects to ensure changes are reactive and propagated to the Virtual DOM using Vue.set method.
<div id="app">
  <div v-for="(item, index) in items" :key="index">
    {{ item.name }} - {{ item.value }}
  </div>
  <button @click="addItem">Add Item</button>
  <button @click="updateFirstItem">Update First Item</button>
</div>
This is the HTML structure with Vue directives. It displays each item in the array with a 'v-for' loop. There are also buttons to trigger methods for adding and updating items.
<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
This script tag includes Vue.js from a CDN, which is necessary for the Vue code to work.
<style>
  #app div {
    margin-bottom: 10px;
  }
</style>
This is the CSS style for the Vue app. It adds a margin to each div that represents an item.
new Vue({
  el: '#app',
  data: {
    items: [
      { name: 'Item 1', value: 100 },
      { name: 'Item 2', value: 200 }
    ]
  },
  methods: {
    addItem() {
      const newItem = { name: `Item ${this.items.length + 1}`, value: this.items.length * 100 };
      this.items.push(newItem);
    },
    updateFirstItem() {
      Vue.set(this.items, 0, { name: 'Item 1', value: 999 });
    }
  }
});
This is the Vue instance. The 'data' object defines the initial array 'items'. The 'methods' object contains two functions: 'addItem' adds a new item to the array, and 'updateFirstItem' demonstrates the correct usage of Vue.set to update the first item in the array reactively.