@Jeanntte
最近因为需要弄一个英文(en)/中文(zh)/西班牙(es)语言的网站,用SSR的Nuxt构建, 再配合vue-i18n去解决切换语言问题
step1 : 安装vue-i18n
npm install vue-i18n --save-dev
step2 : 新增locals文件
在根目录新建locales
新建zh.json / en.json / es.json 按需配置语言(备注: 分别对应 中文 / 英文 / 西班牙)
zh.json
{
"links": {
"home": "首页"
},
"home": {
"title": "欢迎来到首页",
"meta": "这是一个简单的网站"
}
}
en.json
{
"links": {
"home": "Home"
},
"home": {
"title": "Welcome to the homepage",
"meta": "This is a simple website"
}
}
es.json
{
"links": {
"home": "Inicio"
},
"home": {
"title": "Bienvenido a la pagina de inicio",
"meta": "Este es un sitio web simple"
}
}
step3: 在plugins新建i18.ts并配置与配置vuex
- 配置state
export const state = (): Istate => ({
locales: ['en', 'zh', 'es'],
locale: 'zh'
})
- 配置mutations
export const mutations = {
[types.SET_LANG](state, locale) {
if (state.locales.indexOf(locale) !== -1) {
state.locale = locale
}
}
}
- 配置types
export const SET_LANG = 'SET_LANG'
- 在目录plugins新建i18.ts
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import ElementLocale from 'element-ui/lib/locale'
// 加入Vue全局
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',
messages: {
'en': { ...require('~/locales/en.json') , ...enLocale },
'zh': { ...require('~/locales/zh.json'), ...zhLocale },
'es': { ...require('~/locales/es.json'), ...zhLocale },
}
});
app.i18n.path = (link) => {
if (app.i18n.locale === app.i18n.fallbackLocale) {
return `/${link}`;
}
return `/${app.i18n.locale}/${link}`;
}
// 配置element-ui的组件国际化
ElementLocale.i18n((key, value) => app.i18n.t(key, value))
}
step4 : 配置Nuxt的配置文件nuxt.config.ts
用于指定vue-i18n的一些配置文件 nuxt.config.ts
- 配置
nuxt.config.ts文件
import NuxtConfiguration from '@nuxt/config'
const config: NuxtConfiguration = {
.... # 其它配置内容忽略,新增plugins&build.verdor
plugins: [
'~/plugins/i18n.ts'
],
build: {
vendor: ['vue-i18n'],
}
}
export default config
step5: 完结
当点击事件触发切换之后,通过更改切换
this.$i18n.locale = 'zh' | 'es' | 'en';
// 通过切换语言
结语:
切换国际化还是挺方便的,通过自定义与elementUi的语言库,这样就完美了...