VUE JS – How to remove an item from a list?

How to remove a specific item from a list in Vue.js when the item does not have an id?

Make sure you install:

import VueLodash from 'vue-lodash';
const options = { name: 'lodash' };

I will also be using Bootstrap Vue in this example

In your component:


    
  • + -

Now the vue code, it took me a long time to find a neat solution:

 

What did I do?

The first problem I encountered was the generation of a unique id in each element of the object. The solution is to use “this._.uniqueId()” from lodash. But, when you will update your page, you will find out very quickly that you may have conflicting ids, ie: You create an id from 1 to 6, delete them and re-add the fields, duplication of ids will happen at this stage. To go around this, I look each time for the highest id and add it's value to the next id as:

            let highestId = Math.max(...this.datasRadios.map(elt => elt.id));
            let id = parseInt(this._.uniqueId());
            let newId = highestId + id;

By using this method, conflicting ids become be something of the past.

Next, finding the key of my elements was important because a lot of people have solutions, but either they are over complicated or not right for this simple job. I have then used lodash again with “this._.findKey”.

If you do not look for the element key, your script will keep deleting the first(element 0) element each time.

Hope this helps, please leave me a comment below