如何在NuxtJS(Vuex)SPA模式下为所有路由和页面发起API请求
Nuxt SPA模式实现路由访问时拉取后端配置的方案
Nuxt SPA 模式没有服务端初始化钩子nuxtServerInit,可以通过客户端路由拦截实现相同效果,以下是两种可行方案:
方案1:使用全局路由中间件(官方推荐)
Nuxt 内置的路由中间件可以在路由跳转前触发执行,全局中间件会对所有路由生效:- Nuxt3 实现
在middleware目录下新建init.global.ts(文件名带.global后缀会自动注册为全局中间件):
export default defineNuxtRouteMiddleware(async () => { const configStore = useConfigStore() // 替换为你的Pinia/Vuex存储实例 // 请求后端配置存入全局存储 const configRes = await fetch('/api/your-config-endpoint') const config = await configRes.json() configStore.updateConfig(config) })- Nuxt2 实现
首先在middleware目录下新建init.js:
export default async function ({ store, $axios }) { const res = await $axios.get('/api/your-config-endpoint') store.commit('updateConfig', res.data) }然后在
nuxt.config.js中注册为全局中间件:export default { router: { middleware: ['init'] } }- Nuxt3 实现
方案2:注册路由全局守卫
你也可以直接通过插件给路由实例注册beforeEach守卫实现拦截:- Nuxt3 实现
在plugins目录下新建router-interceptor.ts:
export default defineNuxtPlugin((nuxtApp) => { nuxtApp.$router.beforeEach(async (to, from, next) => { const configStore = useConfigStore() const res = await fetch('/api/your-config-endpoint') configStore.updateConfig(await res.json()) next() }) })- Nuxt2 实现
在plugins目录下新建router-interceptor.js:
export default function ({ app, store, $axios }) { app.router.beforeEach(async (to, from, next) => { const res = await $axios.get('/api/your-config-endpoint') store.commit('updateConfig', res.data) next() }) }最后在
nuxt.config.js的plugins数组中注册该插件即可。- Nuxt3 实现
优化提示:如果你的配置不需要每次路由跳转都重新拉取,可以在全局存储中加一个已加载标识,配置拉取成功后标记为已加载,后续路由跳转时直接跳过请求即可,减少不必要的接口开销。
内容的提问来源于stack exchange,提问作者Ahmad Mobaraki
相关产品推荐
相关产品推荐

