需求
如果项目需要国际化,即点击按钮切换 中/英文。那么就需要引入 vue-i18n 插件
安装
首先创建项目
vue init webpack
然后安装 i18n 插件
npm install vue-i18n --save
创建语言包
src/common/lang/en.js
export const lang = {
welcome: 'Welcome to Your Vue.js App',
essential_links: 'Essential Links',
core_docs: 'Core Docs',
forum: 'Forum',
community_chat: 'Community Chat',
twitter: 'Twitter',
docs_for_this_template: 'Docs for This Template',
ecosystem: 'Ecosystem',
vue_router: 'vue-router',
vuex: 'vuex',
vue_loader: 'vue-loader',
awesome_vue: 'awesome-vue'
}
src/common/lang/zh.js
export const lang = {
welcome: '欢迎来到你的Vue.js应用',
essential_links: '基本环节',
core_docs: '核心文档',
forum: '论坛',
community_chat: '社区聊天',
twitter: '推特',
docs_for_this_template: '模板文档',
ecosystem: '生态系统',
vue_router: 'vue路由器',
vuex: 'vue状态管理器',
vue_loader: 'vue文件编译成html文件',
awesome_vue: 'vue图标库'
}
封装插件
src/common/lang/index.js
这里做了3件事
挂载 VueI18n组件到 Vue
将语言列表绑定到 Vue 的 prototype 中,之后就可以在任何地方通过 this 引用该变量了
新建 VueI18n 对象,指定当前语言标识 和 多国语言分别对应的资源列表,然后设置默认导出该变量
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n) // 挂载i18n
Vue.prototype.language = [{ // 挂载全局变量
value: 'en-US',
text: 'English'
},
{
value: 'zh-CN',
text: '中文'
}
]
const i18n = new VueI18n({
locale: 'en-US', // 语言标识,通过this.$i18n.locale来切换语言
messages: {
'en-US': require('./en'), // 英文语言包
'zh-CN': require('./zh') // 中文语言包
}
})
export default i18n
修改模板
src/main.js
引入封装好的i18n变量,并将其添加到Vue的构造对象中
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import i18n from './common/lang/index'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
i18n,
router,
components: { App },
template: ''
})
src/components/HelloWorld.vue
对于绑定到全局里的language列表变量,通过vue的列表功能,将其自动添加到select元素的选项表里面
{{item.text}}
语言列表改变了语言之后,会触发onChange事件,通过修改 this.$i18n.locale 变量可以改变当前页面的语言。
对于需要国际化的变量,需要使用 $t(lang.strId)进行转换,因此需要在 computed 对象中对其进行处理
export default {
name: 'HelloWorld',
data () {
return {
msg: 'welcome'
}
},
methods: {
changeLang (event) {
console.log(event.target.value)
this.$i18n.locale = event.target.value
}
},
computed: {
getMsg: function () {
const str = 'lang.' + this.msg
return this.$t(str)
}
}
}
添加样式,将切换语言的列表固定在页面右上角
position: fixed;
top: 2rem;
right: 4rem;
}
结果展示