Nuxt.js國際化的前提是,已經使用腳手架工具搭建好了Nuxt.js的開發環境。
我使用的環境是nuxt@2.3 + vuetify@1.4 + vue-i18n@7.3
1. 先安裝vue-i18n
npm install --save vue-i18n
2. 更新store文件
在@/store/index.js文件中,修改添加如下代碼:
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
函數
3. 更新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
中的相同
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文件夾
增加對應語言的對照json數據,en-US.json、zh-CN.json等等
其中,兩個json數據,需要相同的key,才能翻譯成功。
{
"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."
}
}
6. 修改nuxt.config.js文件
修改或者增加如下對象:
router: {
middleware: 'i18n'
},
plugins: ['@/plugins/i18n.js'],
generate: {
routes: ['/', '/about', '/zh-CN', '/zh-CN/about']
}
7. 修改pages文件夾下相應的頁面
在pages文件夾下新建_lang
文件夾,之后在此文件夾下新建對應的頁面組件。
例如:
@/pages/_lang/index.vue
@/pages/_lang/about.vue
一定要帶下划線的_lang
,否則params.lang
,獲取不到值。可以參考官網這里
<template >
<div> {{ $t('home.title') }}</div>
</template>
頁面中的需要翻譯的內容,都使用語法$t('')
給包裹起來,其中里面的值,是從@/locales/***.json
文件中獲取對應的key
。
8. 總結
經過以上7個步驟之后,國際化基本可以完成了。完成國際化的過程中,提到了三個需求
- 切換語言,不刷新頁面。【只需要在切換的時候,設置store中的locale值為對應的language值,不做其他操作】
- 刷新頁面之后,還是當前語言。【這個需要將設置好的語言保存起來,放到本地緩存中,是個不錯的選擇】
- 根據瀏覽器的語言,顯示語言。【使用navigator.language來獲取瀏覽器默認語言,之后將其賦值給為store中的locale值】
2、3的優先級,首次進來,根據瀏覽器系統語言決定,刷新的時候,根據緩存決定。最后都需要給store
中的locale
賦值。顯示何種語言,是由$i18n.locale
決定。