Home » Alternative to Vue.delete in Vue 3

Alternative to Vue.delete in Vue 3

  • by

1. Overview

In this article, we will learn the alternative solution to the Vue.delete global API in Vue 3. To learn more about Vue, refer to these articles.

2. Vue.delete API

This global API delete a property on an object. If the object is reactive, ensure the deletion triggers view updates.

The Vue.set API adds a new property to an existing reactive object and triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions or creations.

3. Alternative to Vue.delete in Vue 3

Vue.delete and Vue.set global APIs are not required in Vue 3 anymore. With the new reactivity system using proxies, Vue can detect all changes to reactive data.

So you can use JavaScript delete operator. The delete operator removes a property from an object. If the property’s value is an object and there are no more references to the object, the object held by that property is released automatically.

delete object.property
delete object[property]

object: The name of an object, or an expression evaluating an object.

property: The property to delete.

It returns true or false as a result. For example, the below code does not work in Vue 3. If you execute, you would get the error "TypeError: Cannot read properties of undefined (reading 'delete')".

<script setup>
import { createApp, reactive } from 'vue'
const obj = reactive({ a: 1, b: 2, c: 3 })

</script>

<template>
 <div id="app">
  Object: {{ obj }}
  <hr>
  <template v-for="(item, key) in obj">
    <button @click="Vue.delete(this.obj, key)">Delete key {{ key }}</button>
    <br>
  </template>
  <button @click="obj['z'] = 'Added'">Add key z</button>
 </div>
</template>

By replacing Vue.delete from the above code as delete obj[key] will make it work in Vue 3.

<script setup>
import { createApp, reactive } from 'vue'
const obj = reactive({ a: 1, b: 2, c: 3 })

</script>

<template>
 <div id="app">
  Object: {{ obj }}
  <hr>
  <template v-for="(item, key) in obj">
    <button @click="delete obj[key]">Delete key {{ key }}</button>
    <br>
  </template>
  <button @click="obj['z'] = 'Added'">Add key z</button>
 </div>
</template>

3. Conclusion

To sum up, we have learned the alternative way to use Vue.delete global API in the latest Vue js. Since Vue 3 uses a proxy in the new reactivity system, it can detect all changes to the object. So normal JavaScript delete operator works fine in this case.

Leave a Reply

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