我有一个 AuthService,我在 Nuxt 应用程序的命名空间商店中使用它。我需要将 AuthService 中的突变提交到命名空间存储,但我不知道如何将存储导入到我的 AuthService 中。
我见过将商店导入 JS 文件的示例,但商店是在 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)
}
})
}
}
最佳答案
我想提出一个使用插件的解决方案。
在外部模块( externalModule.js
)中,我们定义 store
变量并导出 init
接收 Nuxt context
的函数作为论据。该函数分配 store
来自 context
到现在可以在模块中使用的变量:
let store;
export function init (context) {
store = context.store;
};
(...further business logic using store)
然后在 plugins 文件夹中创建一个插件文件(我们称之为 storeInit.js
)。该文件导入 init
来自外部模块的函数并导出 Nuxt 所需的默认插件函数。函数接收context
来自 Nuxt,我们称之为 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
.
关于vue.js - 从 JS 文件访问 Nuxt 存储(在模块模式下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218967/