一、安装vue-i18n
npm install vue-i18n 或 yarn add vue-i18n
二、在store文件夹下更新index.js文件
export const state = () => ({
locales: ["en", "zh"],
locale: "zh"
});
export const mutations = {
SET_LANG(state, locale) {
if (state.locales.includes(locale)) {
state.locale = locale;
}
}
};
三、在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: 'zh',
messages: {
zh: require('~/locales/zh.json'),
en: require('~/locales/en.json')
}
})
app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`
}
return `/${app.i18n.locale}/${link}`
}
}
四、在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.includes(locale)) {
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, '/'))
}
}
五、增加locales文件夹
注意:增加对应语言的对照json数据,en.json、zh.json等等。其中,两个json数据,需要相同的key,才能翻译成功。
六、配置nuxt.config.js文件
在配置中添加这两句代码,重新运行才生效。
router: {
middleware: 'i18n'
},
plugins: ['@/plugins/i18n.js'],
七、创建_lang文件夹
在pages文件夹下新建_lang
文件夹,之后在此文件夹下新建对应的页面组件。一定要带下划线的_lang,
否则params.lang,
获取不到值。
八、在pages文件夹下相应的页面应用
页面中的需要翻译的内容,都使用语法$t('')
给包裹起来,其中里面的值,是从@/locales/***.json
文件中获取对应的key
。
<template >
<div> {{ $t('home.title') }}</div>
</template>
以上纯粹个人理解,若有问题,望告知。