如何从变异名称空间模块访问全局状态?

时间:2020-05-31 17:36:24

标签: javascript vue.js

在我的import { Button } from 'antd'; 中,我有两个命名空间模块:<Button type="primary" shape="circle"> hey </Button> state,如下所示:

portfolio

stocks中,我拥有export default new Vuex.Store({ modules: { stocks, portfolio } }) 属性;在stocks中,我拥有stocks属性。我要提交portfolio突变,它需要从funds模块访问BUY_STOCK,从stocks访问stocks。我在funds模块中进行了如下设置:

profile

我得到了profile。这是因为"BUY_STOCK"(state, {stockId, quantity, stockPrice}) { console.log(state.stocks.stocks, state.portfolio.funds) } 只是本地模块状态。如何从这种突变中获取全局状态?

2 个答案:

答案 0 :(得分:0)

您可以从vuex操作上下文访问rootState。除了调用突变,您还可以调用操作:

actions: {
 buyStock(context, {stockId, quantity, stockPrice}) {
    console.log(context.state.funds) // access local state
    console.log(context.rootState.stocks.stocks) // access stocks state through rootState
    // Then call mutations with the retrieved values 
    context.commit("BUY_STOCK", {stockData, portfolioData}) 
  }
}

答案 1 :(得分:0)

似乎您没有导入 profile模块到store / index.js, 所以看起来像这样:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio,
    profile
  }
})

您可能应该考虑在每个模块中使用吸气剂:

portifolio.js

export default {
  state: {
    funds: 'Some funds'
  },
  getters: {
    funds(state) {
      return state.funds
    }
  }
}

stocks.js

export default {
  state: {
    stocks: 'Some stocks'
  },
  getters: {
    stocks(state) {
      return state.stocks
    }
  }
}

现在,您可以像这样从profile模块访问它们:

profile.js

export default {
  actions: {
    BUY_STOCK({ getters }, { stockId, quantity, stockPrice }) {
      console.log(getters.funds, getters.stocks)
    }
  }
}