@Jeannttevue
最近由于须要弄一个英文(en)/中文(zh)/西班牙(es)语言的网站,用SSR的Nuxt构建, 再配合vue-i18n去解决切换语言问题web
vue-i18n
npm install vue-i18n --save-dev
复制代码
在根目录新建locales
vuex
新建zh.json / en.json / es.json 按需配置语言(备注: 分别对应 中文 / 英文 / 西班牙)npm
zh.jsonelement-ui
{
"links": {
"home": "首页"
},
"home": {
"title": "欢迎来到首页",
"meta": "这是一个简单的网站"
}
}
复制代码
en.jsonjson
{
"links": {
"home": "Home"
},
"home": {
"title": "Welcome to the homepage",
"meta": "This is a simple website"
}
}
复制代码
es.jsonbash
{
"links": {
"home": "Inicio"
},
"home": {
"title": "Bienvenido a la pagina de inicio",
"meta": "Este es un sitio web simple"
}
}
复制代码
export const state = (): Istate => ({
locales: ['en', 'zh', 'es'],
locale: 'zh'
})
复制代码
export const mutations = {
[types.SET_LANG](state, locale) {
if (state.locales.indexOf(locale) !== -1) {
state.locale = locale
}
}
}
复制代码
export const SET_LANG = 'SET_LANG'
复制代码
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))
}
复制代码
用于指定vue-i18n的一些配置文件 nuxt.config.tsapp
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 复制代码
当点击事件触发切换以后,经过更改切换async
this.$i18n.locale = 'zh' | 'es' | 'en';
// 经过切换语言
复制代码
结语:fetch
切换国际化仍是挺方便的,经过自定义与elementUi的语言库,这样就完美了...