【问题标题】:Nuxt access store (in Module mode) from JS file从 JS 文件访问 Nuxt 存储(在模块模式下)
【发布时间】:2020-05-29 19:39:00
【问题描述】:

我在我的 Nuxt 应用程序的命名空间存储中使用了一个 AuthService。我需要将 AuthService 中的突变提交到命名空间存储,但我不知道如何将存储导入到我的 AuthService 中。

我已经看到了将 store 导入 JS 文件的示例,但 store 是在 Vue 应用程序中显式定义的。因为我在商店中使用 Nuxt 和 Module 模式,所以我不确定可以将商店导入 AuthService 文件的根路径。据我了解,当使用“模块模式”时,Nuxt 会在后台处理创建根存储和所有命名空间存储

我的 Nuxt store 目录包括 index.js(为空)和 auth.js,其中包含我想从 AuthService 调用的突变。

auth.js

import AuthService from '../firebase/authService'

const authService = new AuthService()

export const state = () => ({
  user: null
})

export const mutations = {
  setUser (state, user) {
    state.user = user
  }
}

export const actions = {
  async signUp ({ commit }, payload) {
    try {
      await authServices.createUser(payload)
      return Promise.resolve()
    } catch (err) {
      const notification = {
        duration: 5000,
        message: err.message,
        type: 'error'
      }
      commit('ui/activateNotification', notification, { root: true })
      return Promise.reject()
    }
  }
}

authService.js

import { fAuth, fDb } from './config'

// I think I need to import auth store here but I'm not sure how

export default class AuthClient {
  async createUser (payload) {
    try {
      const res = await fAuth.createUserWithEmailAndPassword(payload.email, payload.password)
      const { uid } = res.user
      const user = {
        ...payload,
        uid
      }
      await this._createUserDoc(user)
      this._initAuthListener()
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  }

  async _createUserDoc (user) {
    await fDb.collection('users').doc(user.uid).set(user)
  }

  _initAuthListener () {
    fAuth.onAuthStateChanged(async (user) => {
      try {
        if (user) {
          const userProfileRef = fDb.collection('users').doc(user.uid)
          const userProfileDoc = await userProfileRef.get()
          const { uid, userName } = userProfileDoc.data()

          // Here is where I want to call a mutation from the auth store

          this.store.commit('setUser', {
            uid,
            userName
          })
        } else {
          this.store.commit('setUser', null)
        }
      } catch (err) {
        console.log(err)
      }
    })
  }
}

【问题讨论】:

  • 你终于找到解决办法了吗?

标签: vue.js vuex nuxt.js vuex-modules


【解决方案1】:

我想提出一个使用插件的解决方案。

在外部模块(externalModule.js)中,我们定义了store 变量并导出了一个init 函数,该函数接收Nuxt context 作为参数。该函数将 context 中的 store 分配给现在可以在模块中使用的变量:

let store;
export function init (context) {
    store = context.store;
};
(...further business logic using store)

然后在 plugins 文件夹中我们创建一个插件文件(我们称之为storeInit.js)。该文件从外部模块导入init 函数并导出Nuxt 所需的默认插件函数。该函数从 Nuxt 接收context,我们调用init 函数进一步传递context

import { init } from '[pathTo]/externalModule.js';
export default (context, inject) => {
    init(context);
};

然后我们在nuxt.config.js文件中注册插件:

module.exports = {
    ...
    plugins: [
        { src: '~/plugins/storeInit' }
    ],
    ...
}

这样,当应用由 Nuxt 构建并注册插件时,context 对象被传递给外部模块,我们可以使用其中的任何内容,其中包括 store

【讨论】:

  • 非常好的解决方案
【解决方案2】:

在 store 文件夹中的 index.js 文件中,您需要像这样返回 store

import Vuex from 'vuex'
const createStore = () => {
  return new Vuex.Store({
    state: {
      counter: 0
    },
    mutations: {
      increment (state) {
        state.counter++
      }
    }
  })
}

export default createStore

在您的authService.js 文件中,您需要像这样导入商店

import $store from '~/store'

这样您就可以访问您的商店

$store.commit('setUser', null)

我希望这对你有用

重要提示:你不需要安装 vuex,因为它已经附带了 nuxtjs

【讨论】:

  • 但这不会破坏 Nuxt 构建过程吗? Nuxt 指定 store 的 index.js 应该是什么样子,并希望它导出 store 的主要属性(状态、突变等),从中创建 store 的实例。它不需要已经创建的实例。
猜你喜欢
  • 2021-06-17
  • 2020-05-20
  • 2021-06-27
  • 1970-01-01
  • 2021-07-15
  • 2023-03-19
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多