gh_mirrors/fr/frontend-stuff 国际化路由守卫:Vue i18n 导航守卫

【免费下载链接】frontend-stuff 📝 A continuously expanded list of frameworks, libraries and tools I used/want to use for building things on the web. Mostly JavaScript. 【免费下载链接】frontend-stuff 项目地址: https://gitcode.com/gh_mirrors/fr/frontend-stuff

你是否遇到过多语言网站切换时路由错乱、用户体验不一致的问题?本文将通过gh_mirrors/fr/frontend-stuff项目中的实践,详细介绍如何使用Vue i18n结合路由守卫实现流畅的国际化导航体验。读完本文你将掌握:国际化路由设计原则、Vue i18n导航守卫实现方案、多场景适配技巧。

项目环境准备

在开始前,请确保项目已安装相关依赖。通过查看package.json可知,当前项目主要依赖包括express、socket.io等后端服务框架,以及recharts等前端UI库,但未直接包含Vue相关依赖。如需实现Vue i18n导航守卫,需先安装:

npm install vue-i18n vue-router

国际化路由设计方案

路由结构设计

推荐采用前缀式路由设计,在URL中显式声明语言代码,如/zh/home/en/about。这种方式有利于SEO和用户认知,实现代码示例:

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/:lang',
    component: { template: '<router-view />' },
    beforeEnter: (to, from, next) => {
      const lang = to.params.lang
      const supportedLangs = ['zh', 'en', 'ja']
      if (!supportedLangs.includes(lang)) return next('zh')
      return next()
    },
    children: [
      { path: 'home', component: () => import('@/views/Home.vue') },
      { path: 'about', component: () => import('@/views/About.vue') }
    ]
  },
  { path: '/', redirect: '/zh/home' }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

Vue i18n 配置

创建i18n实例并配置语言文件,项目中推荐使用JSON格式存储翻译内容:

// i18n/index.js
import { createI18n } from 'vue-i18n'
import zh from './locales/zh.json'
import en from './locales/en.json'

const i18n = createI18n({
  legacy: false,
  globalInjection: true,
  locale: 'zh',
  fallbackLocale: 'en',
  messages: {
    zh,
    en
  }
})

export default i18n

导航守卫核心实现

全局前置守卫

在路由跳转前检查语言设置,确保i18n locale与URL语言参数同步:

// router/guards/i18nGuard.js
export function setupI18nGuard(router, i18n) {
  router.beforeEach((to, from, next) => {
    const lang = to.params.lang || 'zh'
    
    // 设置i18n语言
    if (i18n.global.locale.value !== lang) {
      i18n.global.locale.value = lang
    }
    
    // 存储当前语言到本地存储
    localStorage.setItem('preferred-lang', lang)
    
    next()
  })
}

路由元信息校验

通过路由元信息定义页面所需语言权限,实现精细化控制:

// router/index.js
const routes = [
  {
    path: '/:lang',
    component: { template: '<router-view />' },
    children: [
      { 
        path: 'admin', 
        component: () => import('@/views/Admin.vue'),
        meta: { 
          requiredLangs: ['zh', 'en'], // 仅支持中英文访问
          auth: true 
        }
      }
    ]
  }
]

// 在全局守卫中添加校验逻辑
router.beforeEach((to, from, next) => {
  // ...其他逻辑
  
  // 语言权限校验
  if (to.meta.requiredLangs && !to.meta.requiredLangs.includes(lang)) {
    return next(`/${to.meta.requiredLangs[0]}${to.path.replace(/^\/[^\/]*/, '')}`)
  }
  
  next()
})

高级应用场景

404页面国际化

结合项目中的错误处理机制,实现多语言404页面:

// router/index.js
const routes = [
  // ...其他路由
  { 
    path: '/:lang/:pathMatch(.*)*', 
    component: () => import('@/views/NotFound.vue') 
  }
]

// NotFound.vue
<template>
  <div>
    <h1>{{ $t('error.404.title') }}</h1>
    <p>{{ $t('error.404.message') }}</p>
    <router-link :to="`/${$i18n.locale}/home`">
      {{ $t('error.404.backHome') }}
    </router-link>
  </div>
</template>

语言切换组件

创建语言切换下拉组件,结合路由守卫实现无缝切换:

<!-- components/LangSwitcher.vue -->
<template>
  <select v-model="selectedLang" @change="changeLang">
    <option value="zh">中文</option>
    <option value="en">English</option>
  </select>
</template>

<script setup>
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'

const { locale } = useI18n()
const route = useRoute()
const router = useRouter()
const selectedLang = locale

const changeLang = () => {
  router.push({
    path: route.fullPath.replace(`/${route.params.lang}`, `/${selectedLang}`)
  })
}
</script>

项目实践与扩展

结合Storybook开发

项目中已集成Storybook(package.json第21、29行),可创建国际化组件故事进行独立开发:

// stories/I18nRouteGuard.stories.js
import { withI18n } from '../.storybook/decorators/withI18n'
import LangSwitcher from '../components/LangSwitcher.vue'

export default {
  title: 'Components/LangSwitcher',
  component: LangSwitcher,
  decorators: [withI18n]
}

export const Default = () => ({
  components: { LangSwitcher },
  template: '<LangSwitcher />'
})

文档与测试

可通过项目的typedoc脚本(package.json第7行)生成API文档,推荐在docs/目录下创建国际化路由守卫专项文档,补充更多使用场景和注意事项。

总结与注意事项

  1. 始终在路由守卫中同步i18n locale与URL参数
  2. 使用fallbackLocale处理未翻译内容
  3. 避免在路由守卫中执行复杂异步操作,影响页面加载速度
  4. 结合localStorage记住用户语言偏好
  5. 为所有路由添加语言参数校验,防止404错误

通过以上方案,可在gh_mirrors/fr/frontend-stuff项目中实现稳定、流畅的国际化导航体验。如需进一步优化,可考虑添加语言切换动画、路由缓存策略等高级特性。

【免费下载链接】frontend-stuff 📝 A continuously expanded list of frameworks, libraries and tools I used/want to use for building things on the web. Mostly JavaScript. 【免费下载链接】frontend-stuff 项目地址: https://gitcode.com/gh_mirrors/fr/frontend-stuff

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐