Alex T
Alex T

Reputation: 3754

Vuex reset store variable when switching route

I'm trying to create a method that brings you back to prevoius route and then resets variable that is stored in vuex. So far I tried doing this: (In the componentfrom template):

<button type="button" class="btn btn-primary btn-lg btn-block" @click="bar">Back</button>

In the component script:

import { mapGetters } from 'vuex'

methods: {
      ...mapGetters([
        'movies'
        ]),
     bar () {
           this.$router.go(-1)
            this.movies=[]
        }
}

And my vuex store:

export const store = new Vuex.Store({
    state:{
        movies : []
    },
    getters: {
        movies: state => {
            return state.movies
        }
    },
    mutations: {
        mutateArray: (state, payload) => {
            state.movies = payload
        }
    },
    actions: {
        updateArray({commit}, payload ){
            commit('mutateArray', payload)
         }
    }
})

Clicking the button brings me to previous route but it seems that the movies state variable is not empty (as there are things displayed on that route indicting its not empty)

Upvotes: 1

Views: 1373

Answers (1)

MartinT
MartinT

Reputation: 644

The problem is that you are mutating state in an incorrect way. What you need is to call the updateArray action with empty payload. In your bar method, it can look something like this:

this.$store.dispatch('updateArray',[]);

Note that this is not not the only solution on how to call an action. For more info visit the docs.

Upvotes: 1

Related Questions