简体   繁体   中英

Commit mutation in a different Vuex module

I got the following structure:

store.js
|
|-- yields.js
|
|--analysis (sub-folder)
          |
          |
          ---actions.js
          |
          ---mutations.js
          |
          ---state.js

In mutations.js I set the date of a state in state.js like:

stateFetchParamsStart: (state, input) => {
  state.fetchParams.start = input;
  // Want to change yields.PRdate too
  //state.yields.PRdate = input;
}

How can I access the PRdate state of yields.js with the mutation from state.js?


EDIT with more information:

I'm setting initial values of PRdate when the component is mounted like:

mounted(){
  ...
  this.fetchPRData(this.pvSystem.system_id); // makes an axios call
}

Also I've set a computed property asking for the date:

getPrDate: {
  get(){
    return this.$store.state.yields.PRdate;
  }
}

Now when clicking on a date picker I want the date to change (also computed propery on a v-model ):

start: {
  get() {
    return this.$store.state.analysis.fetchParams.start
  },
  set(value) {
    this.$store.commit('stateFetchParamsStart', value)
  }
}

You can change a Vuex module's state from another module, but it has to be done through an action . That action can call a mutation in the other module. So first, create a mutation in your yields module:

mutations: {
  statePRdate(state, input) {
    state.PRdate = input;
  }
}

Now you can use an action in the analysis module to commit that mutation. Pass a third argument to the commit call:

{ root: true }

The first argument will be the mutationName or moduleName/mutationName if your modules are namespaced. Here is the new action below that calls both a mutation in its own module and a mutation in another module:

actions: {
  analysisAction({ commit }, input) {
    commit('stateFetchParamsStart', input);         // Commit in this module
    commit('statePRdate', input, { root: true });   // Commit in another module
  }
}

Initiate the action like:

this.$store.dispatch('analysisAction', 'input')

Namespaced modules

If your modules are namespaced, then you'd use namespaced syntax for both the commit and the action:

commit('yields/statePRdate', input, { root: true })
this.$store.dispatch('analysis/analysisAction', 'input')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM