Vue SSR Nuxt 国际化

Vue I18n is internationalization plugin for Vue.js

安装

1
$ npm install vue-i18n --save

使用

~/nuxt.config.js

引入插件,启动中间件

1
2
3
4
plugins: ['~/plugins/i18n.js'],
router: {
middleware: 'i18n',
}

~/plugins/i18n.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
export default ({ app, store }) => {
let data = {}
let Locale = store.state.locales
for (let i = 0; i < Locale.length; i++) {
data[Locale[i]] = require(`~/locales/${Locale[i]}.json`)
}
// 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',
messages: data
})
// 自定义页面跳转方法
app.i18n.path = (link) => {
return `/${app.i18n.locale}/${link}`
}
}

~/middleware/i18n.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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', store.state.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/index.js

创建本地语言库

1
2
3
export default () => {
return ['en', 'fr', 'cn']
}

~/locales/fr.json

更加不同页面添加不用的语言

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"links": {
"home": "Accueil",
"about": "À propos",
"english": "Version Anglaise",
"french": "Version Française"
},
"home": {
"title": "Bienvenue",
"introduction": "Ceci est un texte d'introduction en Français."
},
"about": {
"title": "À propos",
"introduction": "Cette page est faite pour vous donner plus d'informations."
}
}

~/store/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Locale from '~/locales'
export const state = () => ({
locales: Locale(),
locale: Locale()[0]
})
export const mutations = {
SET_LANG(state, locale) {
if (state.locales.indexOf(locale) !== -1) {
console.log(locale)
state.locale = locale
}
}
}

方法

获取

1
$t('links.english')

设置

1
this.$i18n.locale = name

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 安装
  2. 2. 使用
    1. 2.1. ~/nuxt.config.js
    2. 2.2. ~/plugins/i18n.js
    3. 2.3. ~/middleware/i18n.js
    4. 2.4. ~/locales/index.js
    5. 2.5. ~/locales/fr.json
    6. 2.6. ~/store/index.js
  3. 3. 方法
    1. 3.1. 获取
    2. 3.2. 设置
,