vue.jsvuejs2vue-componentvuejs3vue-reactivity

Vue 3 - Vue.delete alternative


What's the alternative of Vue.delete in the new Reactivity API of Vue 3?


Solution

  • Vue.delete and Vue.set aren't needed in Vue 3. With the new reactivity system using proxies, Vue is able to detect all changes to reactive data.

    You can use JavaScript's delete operator:

    delete obj[key]
    

    Here's a Vue 3 demo removing and adding object properties with vanilla JavaScript:

    const { createApp, reactive } = Vue;
    const app = createApp({
      setup() {
        const obj = reactive({ a: 1, b: 2, c: 3 })
        return { obj }
      }
    });
    app.mount("#app");
    <div id="app">
      Object: {{ obj }}
      <hr>
      <template v-for="(item, key) in obj">
        <button @click="delete obj[key]">Delete key {{ key }}</button>
      </template>
      <button @click="obj['z'] = 'Added'">Add key z</button>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.21/vue.global.min.js"></script>