初始化项目
Create Vue 项目和 install vue-i18n
vue create vue-multilang
使用vue-i18n加载语言包
创建语言文件
多语言文件的统一入口,加载各种语言文件
// src/lang/index.js
import zh from './translations/zh.json'
import en from './translations/en.json'
export default {
zh,
en
}
在英文中,button翻译为button,等等
// src/lang/translations/en.json
{
"button": "button",
"color": "color",
"home": "Home",
"about": "About"
}
在中文中,button翻译为按钮,等等
// src/lang/translations/zh.json
{
"button": "按钮",
"color": "颜色",
"home": "首页",
"about": "关于"
}
配置路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import { i18n } from '../main'
import RouterView from '../views/RouterView.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/:lang',
name: 'routerView',
component: RouterView,
beforeEnter: (to, from, next) => {
const lang = to.params.lang;
if (!['zh', 'en'].includes(lang)) return next('zh')
if (i18n.locale !== lang) {
i18n.locale = lang
}
return next()
},
children: [
{
path: 'home',
name: 'home',
component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue')
},
{
path: 'about',
name: 'about',
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
RouterView.vue
<template>
<div>
<router-link :to="'/' + $i18n.locale + '/home'">
{{ $t('home') }}
</router-link>|
<router-link :to="'/' + $i18n.locale + '/about'">
{{ $t('about') }}
</router-link>
<router-view></router-view>
</div>
</template>
About.vue
<template>
<div class="about">
<p>{{ $t('button') }}</p>
</div>
</template>
Home.vue
<template>
<div class="home">
<p>{{ $t('color') }}</p>
</div>
</template>
App.vue
<template>
<div id="app">
切换语言<language-switcher></language-switcher>
<router-view></router-view>
<div></div>
</div>
</template>
<script>
import LanguageSwitcher from './views/LanguageSwitcher'
export default {
components: {
LanguageSwitcher
}
}
</script>
切换语言LanguageSwitcher.vue组件
<template>
<div class="locale-changer">
<select v-model="$i18n.locale">
<option
v-for="(lang, i) in langs"
:key="`Lang${i}`"
:value="lang"
>{{ lang }}</option
>
</select>
</div>
</template>
<script>
export default {
name: 'LanguageSwitcher',
data() {
return { langs: ['zh', 'en'] };
}
};
</script>
可以根据访问的页面地址不同显示不同的语言http://localhost:8080/zh/home
和http://localhost:8080/en/home
,也可以自己手动切换语言。
源码地址:GitHub