vue用i18n实现多语言切换国际化附源码下载
日期:2019-01-29
来源:程序思维浏览:2315次

如果项目需要多语言的支持,我们需要做国际化,使用 vue-i18n 来实现多语言的界面
安装
$ npm install vue-i18n --save
在入口main.js文件配置使用
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n);
/*---------基本使用-----------*/
const i18n = new VueI18n({
locale: 'CN', // 语言标识
messages : {
en: {
message: {
hello: 'hello world'
}
},
cn: {
message: {
hello: '你好、世界'
}
}
}
})
/*---------使用语言包-----------*/
const i18n = new VueI18n({
locale: 'CN', // 语言标识
messages: {
'CN': require('./assets/common/lang/cn'), // 中文语言包
'EN': require('./assets/common/lang/en') // 英文语言包
},
})
/*---------语言包内部语法star-----------*/
export const message = {
language:'语言',
hello: '你好,世界'
}
/*---------语言包内部语法end-----------*/
/*---------挂载全局使用-----------*/
new Vue({
el: '#app',
i18n,
router,
template: '<App/>',
components: { App }
})
/*---------vue组件模板的使用-----------*/
<template>
<p>{{ $t("message.hello") }}</p>
</template>
单独组件的使用
在单个vue组件中使用,要用到i18n自定义块,需要配置webpack文件webpack.base.conf.js
module.exports = {
// ...
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// you need to specify `i18n` loaders key with `vue-i18n-loader` (https://github.com/kazupon/vue-i18n-loader)
i18n: '@kazupon/vue-i18n-loader'
}
}
},
// ...
]
},
// ...
}
示例
<i18n>
{
"en": {
"hello": "hello world!"
},
"ja": {
"hello": "你好,世界!"
}
}
</i18n>
<template>
<div id="app">
<label for="locale">locale</label>
<select v-model="locale">
<option>en</option>
<option>ja</option>
</select>
<p>message: {{ $t('hello') }}</p>
</div>
</template>
<script>
export default {
name: 'app',
data () { return { locale: 'en' } },
watch: {
locale (val) {
this.$i18n.locale = val
}
}
}
</script>
关于语言包,我们有几种方式,一种是每个语言包一个独立的js放到项目里, 或者将语言的对照写在 .vue 文件里, 或者加载远程的JSON语言包
我们的后台界面需要支持的语言通常不多,更新也不会非常的频繁,所以我们将语言包放在项目里,规划项目目录,增加 lang 目录来存放语言对照
新建index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: localStorage.getItem('lang') || 'cn', // 语言标识
messages: {
'cn': require('./cn'), // 中文语言包
'en': require('./en') // 英文语言包
}
})
export default i18n
加载中英双语,然后再分别创建 cn.js和en.js
编写语言对照, 我们按照项目来规划类似main auth nav这样的分组,或者理解为命名空间吧
// cn.js
export const main = {
'logo': '认证管理后台',
'searchbox': '快速搜索',
'profile': '用户中心',
'password': '修改密码',
'logout': '退出登陆',
'lang_cn': '简体中文',
'lang_en': '英文'
}
export const auth = {
'login_title': '用户登陆',
'logout_title': '用户退出',
'username': '用户名',
'password': '密码',
'login': '登陆',
'relogin': '重新登陆',
'register': '注册',
'password_forgot': '忘记密码'
}
export const nav = {
dashboard: '运行状态',
dev: '我的设备',
portal: '认证设置',
network: '网络管理',
stat: '统计分析',
users: '认证用户',
extends: '扩展功能'
}
修改main.js在项目引入i18n
import i18n from './lang'
...
new Vue({
el: '#app',
i18n,
router,
template: '<App/>',
components: { App }
})
在页面html中使用的方式
<div>{{ $t('main.logo') }}</div>
<input type="text" :placeholer="$t('auth.username')" />
在js中使用
data () {
return {
login_title: this.$t('auth.login_title')
}
}
源码下载
精品好课