【问题标题】:How acccess mutation from one store file for another store file?如何从一个存储文件访问另一个存储文件的突变?
【发布时间】:2021-04-22 17:03:42
【问题描述】:

如何从我的store 文件夹中的一个文件访问我的store 文件夹中的另一个文件中存在的突变?

这是我的目录:

store/
     user.js
     loading.js

user.js 我有:

  async googleSignInRedirect({ commit }) {
    try {
      const result = await this.$fire.auth.getRedirectResult()
      if (result.credential) {
        // const credential = result.credential
        // console.log('got a credential? ', credential)
        this.$router.replace('/')
        commit('loading/SET_LOADING', false) //< -- what is correct way to write this ?
      }
      return null
    } catch (error) {
      console.error(error)
    }
  },

这里是loading.js 代码:

export const state = () => ({
  loading: false
})

export const mutations = {
  SET_LOADING(state, payload) {
    state.loading = payload
  }
}

如何从user.js 访问loading.js?如果我执行上述样式,我会在控制台中收到以下错误:

vuex.esm.js?2f62:791 [vuex] unknown local mutation type: loading/SET_LOADING, global type: user/loading/SET_LOADING

【问题讨论】:

    标签: vuex vuex-modules


    【解决方案1】:

    只需将{ root: true } 作为最后一个参数传递给commit,所以:

      async googleSignInRedirect({ commit }) {
        try {
          const result = await this.$fire.auth.getRedirectResult()
          if (result.credential) {
            this.$router.replace('/')
            commit('loading/SET_LOADING', false, { root: true })
          }
          return null
        } catch (error) {
          console.error(error)
        }
      }
    

    您可以在Vuex documentation找到更多详细信息。

    【讨论】:

    • 谢谢!现在我得到错误:Uncaught TypeError: Cannot read property 'registerModule' of undefined。那是因为我被重定向到 Google 登录页面(在我的应用程序之外),然后又返回到我的应用程序?
    • @redshift 这是与您上述问题无关的错误。请注意,使用 Nuxt,您需要在 ~/store 目录中有一个 index.js 文件。
    • 谢谢。我在index.js 文件中放了什么? nuxt 文档使用counter 示例,但我没有计数器...
    • @redshift 你可以只创建一个空文件,或者最多:export const state = () =&gt; ({})
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2013-11-01
    • 2016-08-30
    • 2016-02-10
    • 1970-01-01
    相关资源
    最近更新 更多