You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SSR模式下通过路由参数配置Quasar语言及语言包?

在Quasar SSR模式下通过路由参数设置语言及语言包使用方案

针对你提供的带locale路由参数的配置,以下是SSR环境下的完整实现步骤:

1. 配置支持的语言包

首先在quasar.config.js中声明需要支持的语言,确保Quasar能正确识别和加载对应语言资源:

// quasar.config.js
module.exports = function (ctx) {
  return {
    framework: {
      lang: 'en-US', // 设置默认 fallback 语言
      importLangs: ['zh-CN', 'es-ES'], // 按需添加需要支持的语言代码
      // 若需全量支持可设 allLangs: true,但会增加打包体积,不推荐
    }
  }
}

2. 实现路由守卫localeNavGuard

在路由守卫中处理locale参数,同时兼容SSR服务端与客户端环境的差异:

// src/router/index.js
import { useQuasar } from 'quasar'

// 定义支持的语言列表,需与quasar.config.js中的配置一致
const SUPPORTED_LOCALES = ['en-US', 'zh-CN', 'es-ES']

export const localeNavGuard = async (to, from, next) => {
  const $q = useQuasar()
  // 从路由参数获取目标语言,无参数时使用默认语言
  const targetLocale = to.params.locale || 'en-US'

  // 拦截非法语言参数,跳转到默认语言路由
  if (!SUPPORTED_LOCALES.includes(targetLocale)) {
    const correctedPath = `/en-US${to.fullPath.replace(`/${to.params.locale}`, '')}`
    return next(correctedPath)
  }

  // SSR服务端环境:直接设置语言,确保渲染的HTML是对应语言
  if (process.server) {
    $q.lang.set(targetLocale)
    // 若使用状态管理(如Pinia/Vuex),可将locale存入全局状态,供客户端同步
    // 示例:store.locale = targetLocale
  } 
  // 客户端环境:按需加载未缓存的语言包
  else {
    if (!$q.lang.isLoaded(targetLocale)) {
      const langModule = await import(`quasar/lang/${targetLocale}`)
      $q.lang.set(langModule.default)
    } else {
      $q.lang.set(targetLocale)
    }
  }

  next()
}

3. 客户端同步服务端语言状态

SSR渲染时服务端已设置好语言,客户端需同步该状态避免hydration不匹配,可通过boot文件实现:

// src/boot/locale-sync.js
import { useQuasar } from 'quasar'

export default ({ ssrContext }) => {
  const $q = useQuasar()

  if (process.client) {
    // 从服务端传递的全局状态中读取初始语言(需配合状态管理实现)
    // 或从页面meta标签读取:document.querySelector('meta[name="locale"]')?.content
    const initialLocale = window.__INITIAL_STATE__?.locale || 'en-US'
    
    if (!$q.lang.isLoaded(initialLocale)) {
      import(`quasar/lang/${initialLocale}`).then(lang => {
        $q.lang.set(lang.default)
      })
    } else {
      $q.lang.set(initialLocale)
    }
  }
}

将该boot文件注册到quasar.config.js:

// quasar.config.js
module.exports = function (ctx) {
  return {
    boot: [
      'locale-sync'
    ]
  }
}

4. 优化SEO与默认路由跳转

  • SEO优化:在SSR模板中设置页面lang属性,确保搜索引擎识别页面语言:
<!-- src/templates/index.html -->
<html lang="<%= ctx.lang %>">
  • 默认路由跳转:当用户访问根路径/时,自动跳转到默认语言路由:
// src/router/index.js
router.beforeEach((to, from, next) => {
  if (to.path === '/' && !to.params.locale) {
    next('/en-US')
  } else {
    next()
  }
})

内容的提问来源于stack exchange,提问作者Chiara Ani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 19:56:16