Vuex: Access State From Another Module

后端 未结 6 776
走了就别回头了
走了就别回头了 2021-01-30 08:12

I want to access state.session in instance.js from records_view.js. How is this accomplished?

store/modules/instance.js

相关标签:
6条回答
  • 2021-01-30 08:22

    from an action :

    'contacts:update' ({ commit, rootState }) {
        console.log('rootState', rootState.users.form)
        ......
    
      },
    
    0 讨论(0)
  • 2021-01-30 08:22

    In my case, this is how it worked for me.

    In file ModuleA.js:

    Module A:  
    export const state = {
        parameterInA: 'A'
     }
    export const action = {
        showParameterB() {
        console.log("Parameter B is: " + this.state.B. parameterInB)
    }
    

    In file ModuleB:

    export const state = {
        parameterInB: 'B'
     }
    
    export const action = {
        showParameterA() {
        console.log("Parameter A is: " + this.state.A.parameterInA)
    }  
    

    You will need to import ModuleA & B in the index.js for the root:

    import * as A from 'ModuleA.js'  
    import * as B from 'ModuleB.js'
    

    This way, state parameter can be cross-referenced in sub modules.

    0 讨论(0)
  • 2021-01-30 08:36

    You need to define session in your state like following, to access it in your getters:

    const state = {
      session: ''
    }
    

    You have to write a mutation, which will be called from your actions to set this state value.

    0 讨论(0)
  • 2021-01-30 08:41
    this.$store.state.instance.session
    

    where "instance" is the module name and "session" is the Vuex state variable you're trying to access.

    0 讨论(0)
  • 2021-01-30 08:43

    state references local state and rootState should be used when accessing the state of other modules.

    let session = context.rootState.instance.session;
    

    Documentation: https://vuex.vuejs.org/en/modules.html

    0 讨论(0)
  • 2021-01-30 08:43

    For me I had vuex modules, but needed a mutation to update STATE in a different file. Was able to accomplish this by adding THIS

    Even in the module you can see what global state you have access to via console.log(this.state)

    const mutations = {
    MuteChangeAmt(state, payload) {
    //From user module; Need THIS keyword to access global state
    this.state.user.payees.amount = payload.changedAmt;
     }
    }
    
    0 讨论(0)
提交回复
热议问题