5

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!

1 Answer 1

3

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
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.