gpt4 book ai didi

javascript - 使用 Nuxt.js 中间件检查 firebase 中的登录用户

转载 作者:行者123 更新时间:2023-12-01 03:19:31 25 4
gpt4 key购买 nike

我为我的 Nuxt 应用程序构建了一些中间件。

import api from '~/api/Api.js'

export default function ({router, store}) {
return api.auth().onAuthStateChanged(function (user) {
store.state.user = user
if (user) {

} else {

}
})
}

现在,如何实际访问用户对象?当我从普通组件执行此操作时,它工作正常。传递来存储简单的字符串也可以,但是任何其他操作都不需要,是否需要某种 promise ?谢谢帮助。

最佳答案

来自 Vuex 文档:

The only way to actually change state in a Vuex store is by committing a mutation. Vuex mutations are very similar to events: each mutation has a string type and a handler. The handler function is where we perform actual state modifications (Documentation link)

突变也会触发 Vue 中的 DOM 更新,因此通过提交突变, react 性元素会被更新,而通过发送字符串直接操作状态不会导致 react 性更新。来自 Vuex 文档:

Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically

标题为“Mutations Follow Vue's Reactivity Rules”的部分对此有更详细的概述。

这里需要注意的是,突变仅适用于同步数据。 如果您有异步数据,Vuex 操作将会有所帮助 - 它们可以执行突变并处理异步事件。

由于没有进一步的示例代码,很难评估这里是否存在其他问题,但是我已经包含了一个适用于这种情况的示例存储文件。虽然不是 nuxt 特定的,但原理是相同的:

// store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
user: {},
files: [],
token: ''
}

const mutations = {
logOut (state) {
state.user = null
},
setUser (state, user) {
state.user = user
},
setToken (state, token) {
state.token = token
}
}

const actions = {
logOut: ({ commit }) => commit('logOut'),
setUser: ({ commit }, user) => commit('setUser', user),
setToken: ({ commit }, token) => commit('setToken', token)
}

const getters = {
user: state => state.user,
token: state => state.token,
files: state => state.files
}

export default new Vuex.Store({
state,
getters,
actions,
mutations
})

然后在你的模块中:

import store from '@/store'
import { mapGetters } from 'vuex'

api.auth().onAuthStateChanged(function (user) {
store.dispatch('setUser', user) // .dispatch triggers ACTION, handling async evt
if (user) {

} else {

}
})


export default {
// mapGetters maps getters allowing this.user in script, or {{ user }} in template
computed: mapGetters([
'user',
'files'
])
}

关于javascript - 使用 Nuxt.js 中间件检查 firebase 中的登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45315253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com