【问题标题】:what is rootState in vuejs, vuex contextvuejs中的rootState是什么,vuex上下文
【发布时间】:2020-05-24 00:39:03
【问题描述】:

我试图了解 rootState 与 vuejs、vuex 的关系......但无法用这些关键词找到明确的解释(谷歌或其他论坛):

  • 什么是“根状态”vuejs
  • 了解“根状态”vuejs

谁能解释它是什么,以及我们如何利用它的用途?

【问题讨论】:

  • 好吧,我阅读了文档,我认为如果你的商店中有模块,他们有自己的state,也许你想访问模块之外的状态,所以你会使用rootState
  • 谢谢,但这是一个优势以及为什么?可以分享一下文档吗?

标签: vue.js vuex


【解决方案1】:

为了更好地构建您的代码,您可以将 vuex 存储拆分为不同的模块。请参阅reference

这是我目前正在从事的项目中的商店示例:

在我的项目中,我需要来自 API 的多个数据,因此我决定在此 API 响应之后拆分我的存储,以将属于一个模块的所有功能捆绑在一起。 index.js 用于将所有模块放在一起并导出存储:

...
import categories from './modules/categories'
import transportation from './modules/transportation'
import insurances from './modules/insurances'
import booking from './modules/booking'

Vue.use(Vuex)


export default new Vuex.Store({

    modules: {
        categories,
        transportation,
        insurances,
        booking
    },

    state: {
        // here I have general stuff that doesn't need to be split in modules
    },

    mutations: {
        // general stuff
    },

    actions: {
        // general stuff
    },

    strict: true
})

如果我需要访问index.js 中的一般内容,或者如果我想从另一个模块内部访问模块中的数据,rootState 就变得很重要。

例如:

要进行预订,我需要知道从我的应用的当前用户中选择了哪个类别。为了实现这一点,我只需在操作中使用 rootState 道具:

/modules/categories.js

export default {
    namespaced: true,

    state: {
        categories: [ // data I need acces to ]
    }


/modules/booking.js

actions: {
    async PUT_BOOKING({ state, commit, dispatch, rootState }) {
          // access categories 
          const categories = rootState.categories.categories
          // rootState -> access root 
          // categories -> namespaced module in store
          // categories -> state categorie in namespaced module
    }
}

例如,您也可以将rootGetters 传递给操作。在我的示例中,我的类别模块中有一个getter,它从类别数组(=state 道具)中返回当前选定类别的索引。

async PUT_BOOKING({ state, commit, dispatch, rootState, rootGetters }) {
      // access categories 
      const categories = rootState.categories.categories

      // acces index of selected categorie
      const index = rootGetters['categories/selCategorie']
}

希望我的例子是可以理解的,我可以帮助你一点。

【讨论】:

    猜你喜欢
    • 2018-04-28
    • 2017-06-29
    • 2021-05-08
    • 2017-11-30
    • 1970-01-01
    • 2012-08-27
    • 2021-01-16
    • 2014-01-24
    • 1970-01-01
    相关资源
    最近更新 更多