vue2-使用vue-i18n搭建多语言切换环境

安装

注意:vue2.0要用8版本的,使用9版本的会报错

npm install [email protected] --save

创建相关的语言包文件

在src目录下,新建i18n文件夹

在新文件夹i18n中新建langs文件夹,里边放语言文本文件.js
      zh.js:存放所有的中文显示内容
      en.js:存放所有的英文显示内容
 与langs文件夹同级,创建index.js:用于配置i18n,并导出i18n

 

zh.js
export default {
    //中文
    变量名:"中文"
}

en.js
export default {
    //英文
    变量名:"英文"
}

index.js
import Vue from "vue"
import VueI18n from "vue-i18n"
//引入自定义语言配置  
import zh from './langs/zh'
import en from './langs/en'
import fan from './langs/fan'

Vue.use(VueI18n); // 全局注册国际化包

// 准备翻译的语言环境信息
const i18n = new VueI18n({
  locale: sessionStorage.getItem('lang') || "简", //将语言标识存入localStorage或sessionStorage中,首次默认中文显示,非首次则以localStorage为准
  messages: {
    // 繁体语言包
    '繁': {
      ...fan
    },
    // 中文语言包
    '简': {
      ...zh
    },
    //英文语言包
    'ENG': {
      ...en
    }
  },
  silentTranslationWarn: true, //解决vue-i18n黄色警告"value of key 'xxx' is not a string"和"cannot translate the value of keypath 'xxx'.use the value of keypath as default",可忽略
  globalInjection: true, // 全局注入
  fallbackLocale: '简', // 指定的locale没有找到对应的资源或当前语种不存在时,默认设置当前语种为中文
});

export default i18n

在main里导入语言包文件

main.js
import i18n from './i18n'

Vue.use(
  {
    i18n: (key, value) => i18n.t(key, value) // 在注册Element时设置i18n的处理方法,可以实现当点击切换按钮后,elementUI可以自动调用.js语言文件实现多语言切换
  }
)

new Vue({
  render: h => h(App),
  i18n
}).$mount('#app')

切换语言

this.$i18n.locale = "ENG";//切换为英文

基本使用

1.在模板字符串中使用
{
   
   { $t("变量名") }}
<button>{
   
   { $t("submit") }}</button>

2.绑定属性使用
:属性名="$t('变量名')"
<input type="text" :placeholder="$t('FromSub.content.placeholder1')"/>
3.在script中使用
this.$t('变量名')

注意:用这种方法在data(){}中获取的变量存在更新this.$i18n.locale的值时无法自动切换的问题,需要刷新页面才能切换语言。

解决方案:

1)调整写法

2)写在计算属性computed:{…}中,不要写在data(){return{…}}中

4.变量名不固定
{
   
   { $t(`msg.${msgss}`) }}//msgss是一个变量

猜你喜欢

转载自blog.csdn.net/weixin_46479909/article/details/134848376