Vue3+vite+vite-plugin-vue-i18n实现本地化URL报guard.call错误如何解决?
错误原因
- 核心错误在于你给路由父组件的
beforeRouteEnter、beforeRouteUpdate两个路由守卫钩子赋值了字符串类型的路径:这两个钩子本质是生命周期回调函数,路由执行守卫逻辑时会尝试调用该函数,传入非函数类型的值就会抛出guard.call is not a function的报错。 - 次要问题:你当前的路由规则是初始化时写死的locale值,仅能匹配初始化读取到的语言对应的路径,用户后续切换语言后新的语言前缀路径无法被路由识别。
修复方案
先移除错误的守卫配置,同时将路由前缀改为动态参数匹配,补充全局守卫处理语言重定向逻辑即可,修改后的完整代码如下:
import {createRouter, createWebHistory} from "vue-router"; import Home from '../pages/Home.vue' import About from '../pages/About.vue' import i18n from '../locales/i18n' // 优先从localStorage取语言,没有就用默认en const getDefaultLocale = () => localStorage.getItem('lang') || 'en' const routes = [ { path: '/', redirect: () => `/${getDefaultLocale()}` }, { // 把locale改成动态路由参数,适配所有语言前缀 path: '/:locale', component: { render(h) { return h('router-view'); } }, children: [ { path: '', name: 'home', component: Home, }, { path: 'about', name: 'about', component: About, } ] } ] const router = createRouter({ history: createWebHistory(), routes, }) // 全局前置守卫处理语言同步 router.beforeEach((to, from, next) => { const locale = to.params.locale || getDefaultLocale() // 同步i18n的语言设置 if(i18n.locale !== locale) { i18n.locale = locale localStorage.setItem('lang', locale) } next() }) export default router;
如果需要切换语言的同时同步修改路由路径,可以在语言切换下拉框的选中回调里加如下逻辑:
// lang为选中的新语言代码 router.push(`/${lang}/${router.currentRoute.value.fullPath.replace(/^\/[^\/]+/, '')}`)
内容的提问来源于stack exchange,提问作者Olivier
相关产品推荐
相关产品推荐

