赞
踩
Vue工程,需要实现多语言切换功能。
npm中对vue-i18n的描述及文档
Internationalization plugin for Vue.js
https://www.npmjs.com/package/vue-i18n
我们将使用这个插件实现多语言。
支持Vue.js 2.x以上版本
npm install vue-i18n
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const messages = {
//英文
en: {
message: {
hello: 'hello',
about: 'about',
welcome: "Welcome"
}
},
//简体中文
zhCHS: {
message: {
hello: '你好',
about: '关于',
welcome: "欢迎"
}
},
//繁体中文
zhCHT: {
message: {
hello: '妳好',
about: '關於',
welcome: "歡迎"
}
}
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
const i18n = new VueI18n({
//定义默认语言
locale: 'en',
messages
})
new Vue({
el: '#app',
router,
i18n, //<====
template: '<App/>',
components: { App }
})
注意:这里是$t
h3 {{ $t("message.hello") }}
完成上述功能后,我们运行,可以看到内容显示为hello
,修改上述第三步的locale
为zhCHS
后运行,可以看到页面变为了你好
。
computed:{
welcomeMessage(){
return this.username + ', '+ this.$t("message.welcome");
}
},
实际项目中,往往需要动态切换语言,比如当用户点击了其需要的语言。
vue-i18n 提供了一个全局配置参数叫 “locale”,通过改变 locale 的值可以实现不同语言的切换。
在页面中只需要在切换时,修改this.$i18n.locale
的值即可。
this.$i18n.locale='zhCHS'
实际开发中,语言资源会很多,通常会单独作为语言包的文件放置在工程中。
在根目录下的static文件夹中新建lang文件夹,作为语言包。
将不同语言保存成json对象,完成3个js如下。
//en.js
module.exports={
message: {
hello: 'hello',
about: 'about',
welcome: "Welcome"
}
}
//zhCHS.js
module.exports={
message: {
hello: '你好',
about: '关于',
welcome: "欢迎"
}
}
//zhCHT.js
module.exports={
message: {
hello: '妳好',
about: '關於',
welcome: "歡迎"
}
}
import LangEn from '../static/lang/en'
import LangZhCHS from '../static/lang/zhCHS'
import LangZhCHT from '../static/lang/zhCHT'
const i18n = new VueI18n({
locale: 'en',
messages:{
'en': LangEn,
'zhCHS': LangZhCHS,
'zhCHT': LangZhCHT
}
})
在开发过程中遇到key对应的内容中,需要进行换行的。用<br>
或者<br />
都会直接将字符输出到页面。
解决方式:将内容写入绑定元素的v-html
中。
例如:
"wish_you_good_luck": "Wishing You a Year of Prosperity. <br /> Good Fortune Starts Here!"
p(v-html='$t("message.wish_you_good_luck")')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。