【发布时间】: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