Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a specific item from array in Vuex

I'm still in the process of learning vue.js and in the middle of a small project to help me learn more about creating a larger scale app using Vuex.

I'm running into an issue where I'm trying to remove a specific item from an array using a button in the app; I can't seem to get the syntax right to do this in Vuex. Here's what I'm working with:

store

const state = {
    sets: [{}]
}

export const addSet = function ({ dispatch, state }) {
    dispatch('ADD_SET')
}

const mutations = {
    ADD_SET (state) {
        state.sets.push({})
    },
    REMOVE_SET (state, set) {
        state.sets.$remove(set)
    }
} 

actions

export const removeSet = function({ dispatch }, set) {
    dispatch('REMOVE_SET')
}

getters

export function getSet (state) {
    return state.sets
}

app

<div v-for="set in sets"> 
    <span @click="removeSet">x</span>
    <Single></Single>
</div>

I have an action set up that will add a blank item to the array that will place a new component in the app when you click an add item button, just not sure how to add a remove item button to each component and have that work.

I hope this makes sense!

like image 484
Mr.Richway Avatar asked Oct 19 '22 03:10

Mr.Richway


1 Answers

You'll need to modify your removeSet function to dispatch the set object that you want to remove from the store:

export const removeSet = function({ dispatch }, set) {
   dispatch('REMOVE_SET', set)
}

Then in your component, you can invoke the action via the @click event as you have it, but you'll need to pass the set object:

<div v-for="set in sets"> 
   <span @click="removeSet(set)">x</span>
   <Single></Single>
</div>

Finally, don't forget to register your getters and actions in your component:

vuex: {
   getters: {
      getSet
   },
   actions: {
      addSet, removeSet
   }
}
like image 150
Nik Avatar answered Oct 27 '22 11:10

Nik