当前位置: 首页 > 工具软件 > vue-toy > 使用案例 >

使用vue-i18n进行国际化

束建章
2023-12-01

一、相关资源

vue-i18n官网,csdn上一个可以练手的项目,这里是github地址,还有博客园上一个写的不错的文章。不过看这两篇文章最后先学过element-ui。
vue-i18n是一个前端国际化的工具,github地址
兼容vue2.00+。

二、实现国际化

1、安装
$ npm i vue-i18n -D
2、在main.js中将vue-i18n注入到vue实例中

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VuI18n)

const i18n = new VueI18n({
 locale: 'zh-CN',//通过切换locale的值来实现语言切换
 messages: {
  'zh-CN': require('./common/lang/zh'),
  'en-US': require('./common/lang/en')
 }
})

new Vue({
 el: '#app',
 i18n,//
 store,
 router,
 template: '<App/>',
 components: { App }
})

3、实现语言包
en.js:

export const m = {
 toy: 'toy',
 animals: 'animals',
 plants: 'plants'
}

zn.js:

export const m = {
 toy: '玩具',
 animals: '动物',
 plants: '植物'
}

4、实现切换

通过改变this.$i18n.locale的值进行切换
在组件中绑定点击事件:

changeLangEvent(){
 this.$confirm('确定切换语言吗?','提示',{
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning'
 }).then(() => {
  if(this.lang === 'en-CN'){
   this.lang = 'en-US';
   this.$i18n.locale = this.lang;//设置
  }else {
   this.lang = 'en-CN';
   this.$i18n.locale = this.lang;//设置
  }
 }).catch(() => {
  this.$message({
   type: 'info',
  });
 });
}

5、在组件里的数据渲染模板
与普通vue对文字的渲染不同的是多了一个$t('')
v-text:

<span v-text="$t('m.toy')"></span>

{{}}:

<span>{{$t('m.toy')}}</span>

三、语言包非静态化

3.1HTML格式
有时我们需要语言包不是静态字符串,而是HTML串。
比如下面这样

export const m = {
 toy: 'toy<br> boots',
 animals: 'animals',
 plants: 'plants'
}

这样的话,我们的数据渲染模板需要有所改变。
在Vue1中,(注意三个花括号)

<p>{{{ $t('m.toy') }}}</p>

在vue2中,(vue 2.0中不推荐使用三个括号,并用v-html替换)

<p v-html="$t('m.toy')"></p>

输出结果将是这样的

<p>toy
<!--<br> exists but is rendered as html and not a string-->
boots</p>

3.2命名格式(Named formatting)

var locales = {
 en: {
  message: {
   hello: '{msg} world'
  }
 }
}

模板是这样的:

<p>{{ $t('messsage.hello',{msg: 'Damn'}) }}</p>

输出是这样的:
<p>Dame world</p>
3.2列表格式

var locales = {
 en: {
  message: {
   hello: '{0} world'
  }
 }
}

模板如下:

<p>{{ $t('message.hello',['beatiful']) }}</p>

输出如下:

<p>beatiful world</p>
 类似资料: