Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex Modules Mutations

Tags:

vue.js

vuex

I need to call vuex module it doesn't work. I've seen the documentation but still it doesn't work. Hope someone can help me.

const stateLocations ={

    state: {

        provinces: {},
        cities: {}
    },
    mutations: {
        provinces(state, payload){

            state.provinces = payload
        }
    }
}


const store = new Vuex.Store({

    modules: {
        locations: stateLocations
    }


})

My code to call the mutations

created(){

            var store = this.$store

            axios.get('api/provinces')
                .then( function(response){

                    store.state.locations.commit('provinces', response.data)
                })
                .catch()
        }

This one doesn't work store.state.locations.commit('provinces', response.data) TY

like image 921
Rbex Avatar asked May 14 '17 07:05

Rbex


People also ask

What are mutations in Vuex?

In Vuex, mutations are synchronous transactions: store. commit('increment') // any state change that the "increment" mutation may cause // should be done at this moment. To handle asynchronous operations, let's introduce Actions.

How would you commit a mutation from another module Vuex?

To change another module state from one module in Vuex, we can call commit with the mutation name with the root option set to true . commit("TOGGLE_LOADING", null, { root: true }); to call commit to commit the TOGGLE_LOADING mutation with root set to true .

How do you mutate Vuex state?

Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations.

What is the difference between Vuex mutations and actions?

Mutations are intended to receive input only via their payload and to not produce side effects elsewhere. While actions get a full context to work with, mutations only have the state and the payload .


1 Answers

Because you didn't enable namespaced in the module, you simply need to

this.$store.commit('provinces', response.data)

If you want to enable namespace:

const stateLocations = {
  namespaced: true,
  state: {
    ...

then you commit the mutation like this:

this.$store.commit('locations/provinces', response.data)
like image 140
CodinCat Avatar answered Sep 21 '22 20:09

CodinCat