Nuxt项目nuxtServerInit仅刷新生效,用户登录无重载不触发如何处理?
问题原因
nuxtServerInit 仅在Nuxt服务端渲染的首次页面加载/全局刷新阶段触发,用户在客户端完成登录属于前端路由侧的交互,不会触发服务端渲染流程,因此该方法不会执行。
解决方案
步骤1:抽离公共的鉴权数据拉取逻辑为独立Vuex action
将你原本写在nuxtServerInit里的拉取逻辑抽出来,避免代码重复:
// store/index.js export const actions = { async nuxtServerInit({ dispatch, commit }) { if (this.$auth.loggedIn) { // 直接调用抽离的公共action await dispatch('fetchAuthRequiredData') } }, // 新增公共拉取action async fetchAuthRequiredData({ commit }) { await Promise.all([ (async () => { const response = await this.$axios.get('api/all/users') commit('setUsers', response.data) })(), (async () => { const response = await this.$axios.get('api/all/teams') commit('setTeams', response.data) })(), (async () => { const response = await this.$axios.get('api/all/clubs') commit('setClubs', response.data) })(), ]) }, // 可选:新增登出时清空数据的逻辑,避免数据残留 clearAuthData({ commit }) { commit('setUsers', []) commit('setTeams', []) commit('setClubs', []) } }
步骤2:登录成功后主动触发该action
有两种常用的触发方式可选:
- 如果你的登录逻辑是自定义实现的,在登录接口调用成功、确认登录状态生效后,直接调用:
// 你的登录方法所在位置 async handleLogin() { // 原有登录逻辑,比如调用登录接口、设置token等 await loginApi(formData) // 新增:触发拉取鉴权数据的action await this.$store.dispatch('fetchAuthRequiredData') // 后续跳转逻辑 this.$router.push('/dashboard') } - 如果你用的是官方
@nuxtjs/auth模块,可以通过插件监听登录事件全局触发:- 先在
nuxt.config.js里注册auth插件:
// nuxt.config.js export default { auth: { plugins: [ '~/plugins/auth.js' ] } }- 新增
plugins/auth.js文件写监听逻辑:
export default function ({ $auth, store }) { $auth.onLoggedIn(() => { store.dispatch('fetchAuthRequiredData') }) // 可选:监听登出事件清空数据 $auth.onLoggedOut(() => { store.dispatch('clearAuthData') }) } - 先在
可选兜底方案
如果怕存在异常场景数据没加载,可以在需要用到这些数据的页面的fetch钩子中做判断,如果数据为空就主动拉取:
// pages/dashboard.vue export default { async fetch({ store, $auth }) { if ($auth.loggedIn && !store.state.users.length) { await store.dispatch('fetchAuthRequiredData') } } }
内容的提问来源于stack exchange,提问作者EECode
相关产品推荐
相关产品推荐

