1、先安装 vue-i18n
npm install --save vue-i18n
2、在 nuxt.js 中引入 vue-i18n
在 ~/plugins 目录下添加文件: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 中的要相同
3、在vuex中保存当前语言状态
在 ~/store 文件中添加文件 index.js
export const state = () => ({
locales: ['en-US', 'zh-CN'],
locale: 'zh-CN'
})
export const mutations = {
// 此处为设置locale
SET_LANG(state, locale) {
if (state.locales.indexOf(locale) !== -1) {
state.locale = locale
}
}
}
4、在 ~/middleware 文件下添加文件 i18n.js,用来控制语言切换
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, '/')
)
}
}
5、创建本地语言包
增加 locales 文件夹,创建en-US.json, zh-CN.json两个文件
eg : zh-CN.json
{
"english": "简体中文",
}
eg : en-US.json
{
"english": "English",
}
6、修改 nuxt.config.js 文件
router: {
middleware: 'i18n'
},
plugins: [
'@/plugins/i18n.js',
// '@/plugins/iview'
],
generate: {
// 这里可能是指定路由
routes: ['/', '/about', '/zh-CN', '/zh-CN/about']
},
7、修改 pages 文件夹下相应的页面
在 pages 文件夹下新建 _lang 文件夹,之后在此文件夹下新建对应的页面组件。
eg: pages/_lang/index.vue, 一定要带下划线的 _lang,否则 params.lang 获取不到值
<template >
<div> {{ $t('home.title') }}</div>
</template>
页面中的需要翻译的内容,都使用语法$t('')给包裹起来,其中里面的值,是从@/locales/***.json文件中获取对应的key
8、总结
经过以上7个步骤之后,国际化基本可以完成了。完成国际化的过程中,提到了三个需求
1、切换语言,不刷新页面。【只需要在切换的时候,设置store中的locale值为对应的language值,不做其他操作】
2、刷新页面之后,还是当前语言。【这个需要将设置好的语言保存起来,放到本地缓存中,是个不错的选择】
3、根据浏览器的语言,显示语言。【使用navigator.language来获取浏览器默认语言,之后将其赋值给为store中的locale值】
2、3的优先级,首次进来,根据浏览器系统语言决定,刷新的时候,根据缓存决定。最后都需要给store中的locale赋值。显示何种语言,是由$i18n.locale决定。