Nuxt.js国际化的前提是,已经使用脚手架工具搭建好了Nuxt.js的开发环境。
我使用的环境是nuxt@2.3 + vuetify@1.4 + vue-i18n@7.3vue
npm install --save vue-i18n
在@/store/index.js文件中,修改添加以下代码:npm
export const state = () => ({ locales: ['en-US', 'zh-CN'], locale: 'en-US' }) export const mutations = { SET_LANG(state, locale) { if (state.locales.indexOf(locale) !== -1) { state.locale = locale } } }
注意,是mutations
对象下的SET_LANG
函数json
在此目录下,添加文件:i18n.js浏览器
import Vue from 'vue' import VueI18n from 'vue-i18n' Vue.use(VueI18n) export default ({ app, store }) => { // Set i18n instance on app // This way we can use it in middleware and pages asyncData/fetch app.i18n = new VueI18n({ locale: store.state.locale, fallbackLocale: 'en-US', messages: { 'en-US': require('@/locales/en-US.json'), 'zh-CN': require('@/locales/zh-CN.json') } }) app.i18n.path = (link) => { // 若是是默认语言,就省略 if (app.i18n.locale === app.i18n.fallbackLocale) { return `/${link}` } return `/${app.i18n.locale}/${link}` } }
messages
对象的key要和state.locales
中的相同缓存
在此目录下,添加文件: i18n.jsapp
export default function({ isHMR, app, store, route, params, error, redirect }) { const defaultLocale = app.i18n.fallbackLocale // If middleware is called from hot module replacement, ignore it if (isHMR) return // Get locale from params const locale = params.lang || defaultLocale if (store.state.locales.indexOf(locale) === -1) { return error({ message: 'This page could not be found.', statusCode: 404 }) } // Set locale store.commit('SET_LANG', locale) app.i18n.locale = store.state.locale // If route is /<defaultLocale>/... -> redirect to /... if (locale === defaultLocale && route.fullPath.indexOf('/' + defaultLocale) === 0) { const toReplace = '^/' + defaultLocale + (route.fullPath.indexOf('/' + defaultLocale + '/') === 0 ? '/' : '') const re = new RegExp(toReplace) return redirect( route.fullPath.replace(re, '/') ) } }
增长对应语言的对照json数据,en-US.json、zh-CN.json等等
其中,两个json数据,须要相同的key,才能翻译成功。async
{ "links": { "home": "Home", "about": "About", "english": "English version", "chinese": "简体中文" }, "home": { "title": "Welcome", "introduction": "This is an introduction in English." }, "about": { "title": "About", "introduction": "This page is made to give you more informations." } }
修改或者增长以下对象:ide
router: { middleware: 'i18n' }, plugins: ['@/plugins/i18n.js'], generate: { routes: ['/', '/about', '/zh-CN', '/zh-CN/about'] }
在pages文件夹下新建_lang
文件夹,以后在此文件夹下新建对应的页面组件。
例如:
@/pages/_lang/index.vue
@/pages/_lang/about.vue
必定要带下划线的_lang
,不然params.lang
,获取不到值。能够参考官网这里函数
<template > <div> {{ $t('home.title') }}</div> </template>
页面中的须要翻译的内容,都使用语法$t('')
给包裹起来,其中里面的值,是从@/locales/***.json
文件中获取对应的key
。工具
通过以上7个步骤以后,国际化基本能够完成了。完成国际化的过程当中,提到了三个需求
二、3的优先级,首次进来,根据浏览器系统语言决定,刷新的时候,根据缓存决定。最后都须要给store
中的locale
赋值。显示何种语言,是由$i18n.locale
决定。