- 使用
vue-i18n
实现国际化,多语言数据保存在locales
文件夹内; - 通过URL的
params
与vuex
共同维护当前语言状态; - 路由改变时触发
middleware/i18n.js
中间件,如果当前路由不包含多语言即params.lang
为空,重定向到当前语言。 最后调用commit('SET_LANG')
,并修改i18n.locale
。
nuxt.config.js
前端路由国际化处理
router: { // 国际化中间件 middleware: 'i18n', extendRoutes (routes) { // 路由国际化处理 routes.forEach((r) => { if (r.path === '/') { r.path = `/:lang(${locales.join('|')})?` } else { r.path = `/:lang(${locales.join('|')})?${r.path}` } }) ... },
./pugins/i18n.js
国际化插件初始化vue-i18n
import Vue from 'vue'import VueI18n from 'vue-i18n'import zhCn from '@/locales/zh-cn'import enUs from '@/locales/en-us'import zhHk from '@/locales/zh-hk'Vue.use(VueI18n)export default ({ app, store }) => { app.i18n = new VueI18n({ locale: store.state.locale, fallbackLocale: 'en-us', messages: { 'zh-cn': zhCn, 'zh-hk': zhHk, 'en-us': enUs } })}
./locales
国际化文件目录
locales├─zh-hk| ├─index.js //导出语言模块| ├─modules // 多语言模块化 | | ├─about.js| | ├─business.js| | └index.js // 扫描modules目录整合所有模块├─zh-cn| ├─index.js| ├─modules| | ├─about.js| | ├─business.js| | └index.js├─en-us| ├─index.js| ├─modules| | ├─about.js| | ├─business.js| | └index.js
/locales/zh-hk/modules/index.js
整合模块,项目中多处使用
// 扫描目录,整合所有模块const files = require.context('.', false, /\.js$/)const modules = {}files.keys().forEach((key) => { if (key === './index.js') { return } modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default})export default modules
./client/middleware
国际化中间件
export default function ({ isHMR, app, store, params, error, req, route, redirect }) { // 未匹配到任何路由 if (!route.matched || route.matched.length <= 0) { return error({ message: 'This page could not be found.', statusCode: 404 }) } // nodemon热更新忽略 if (isHMR) { return } // 确定当前语言 const locale = params.lang || store.state.locale || app.i18n.fallbackLocale // 重定向到多语言 if (!params.lang & route.fullPath === '/') { return redirect(`/${locale}`) } else if (!params.lang) { return redirect(`/${locale}${route.fullPath}`) } // 设置语言 store.commit('SET_LANG', locale) app.i18n.locale = store.state.locale}
文章转载于:https://www.jianshu.com/p/6b44301b05e2
原著是一个有趣的人,若有侵权,请通知删除
还没有人抢沙发呢~