What's the alternative of Vue.delete in the new Reactivity API of Vue 3?
            Asked
            
        
        
            Active
            
        
            Viewed 1.2k times
        
    13
            
            
         
    
    
        Dan
        
- 59,490
- 13
- 101
- 110
 
    
    
        nitrovatter
        
- 931
- 4
- 13
- 30
2 Answers
23
            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://unpkg.com/vue@next"></script> 
    
    
        Dan
        
- 59,490
- 13
- 101
- 110
- 
                    1My implementation is a little... custom... but I'm trying to delete a particular key/value out of an object in the vuex store. It deletes just fine, but my computeds drawing from the object aren't updating. Is vuex working differently, or did I probably screw up something else? – Randy Hall Feb 13 '22 at 03:08
- 
                    2@RandyHall Vuex is no different. You can even delete the key w/o an action and it would still work (but you probably should use an action). Here's the same demo above using Vuex state, and buttons to delete a key with an action or without: https://jsfiddle.net/sh0ber/5t4bpwks/ – Dan Feb 13 '22 at 04:47
- 
                    1@Dan thanks for the explanation! My particular bug turned out to be a developer (me) issue, but this is great to know – Randy Hall Feb 13 '22 at 17:53
0
            
            
        For arrays, using the splice method is the correct way to go.
const numbers = ['0', '1', '2', '3'];
numbers.splice(1,1); // Array ["0", "2", "3"]
While the delete operator works on arrays too, using it creates a sparse array whose length won't be updated and the element previously at the deleted index will be undefined. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete?retiredLocale=de#deleting_array_elements
This can lead to problems when using the array later, e.g. with v-for="number in numbers" in a vue template.
 
    
    
        Raimund Schlüßler
        
- 13
- 5