vue3实战-- 结合element-ui和vant框架实现国际化多语言切换

有时我们在项目中会用到多个国家语言的切换,这时候我们就不能把内容写死了,而是借助工具实现语言的转换。

今天介绍的这个就是开源的 vue-i18n ,如何使用以及如何结合element-uivant-ui框架混合使用

首先,第一步我们要先学会在项目中如何去使用,才能进行下一步切换ui框架的内置语言,后边会以element-uivant ui两个ui框架为例

安装:

npm i vue-i18n -S

在assets项目下写了几个js文件,cn.js是英文,en.js是中文,index.js是输出文件,vantLocal.js是专门为vant ui切换语言的方法(一个练习中英文切换的demo,更多语言请自行配置)

en.js

const message =  {
    hello: 'hello',
    about: 'about',
    welcome: "Welcome"
  }
  export default message;

cn.js

const message =  {
    hello: '你好',
    about: '关于',
    welcome: "欢迎"
  }
export default message;

index.js

import en from './en'
import cn from './cn'
const messages = {
    en: {
        message:en
    },
    zhCHS: {
        message:cn
    }
}
export default messages;

vantLocal.js

import { Locale } from 'vant';
import enUS from 'vant/lib/locale/lang/en-US';
import zhCN from 'vant/lib/locale/lang/zh-CN';
export function Locals(a){
    if(a == 'en'){
        Locale.use('en', enUS);
    }else if(a == 'zhCHS'){
        Locale.use(a, zhCN);
    }
}

在main.js中使用(自行引入其他的Vue,element-ui,vant等组件,这里为了方便观察,只写了核心代码)

import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
  //定义默认语言
  locale: 'en', 
  messages
})

locale.i18n((key, value) => i18n.t(key, value)) //方便element使用,其内部封装也是采用的i18n
/*vue上挂在vant i18n方法*/
import {Locals} from './assets/lang/vantLocal.js'
Vue.prototype.$Local = Locals

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

在vue结构中:

直接通过{{$t(...)}}

在js中通过this.$("...")获取值

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="cn">切换中文</button>
    <button @click="en">切换英文</button>
    h3 {{ $t("message.hello") }}
    <h1>{{$t('message.welcome')}}</h1>
    <div @click="top">饿了么测试</div>
    <demo></demo>
    <!-- vant组件 -->
    <van-datetime-picker
  v-model="currentDate"
  type="datetime"
  :min-date="minDate"
  :max-date="maxDate"
/>
  </div>
</template>

<script>
import demo from './home-demo'
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return{

      minHour: 10,
       maxHour: 20,
       minDate: new Date(),
       maxDate: new Date(2019, 10, 1),
       currentDate: new Date()
    }
  },
  methods:{
    cn(){
      this.$i18n.locale='zhCHS'
      this.$Local('zhCHS')
    },
    en(){
      this.$i18n.locale='en'
      this.$Local('en')
    },
    top(){//element-ui的弹窗组件
      this.$alert(this.$t('message.welcome'),this.$t('message.welcome'), {
        confirmButtonText: this.$t('message.welcome')
      });
    }
  },
  components:{
    demo
  }
}
</script>

一起看下结果

中文:

英文:(为了便于观察,窗口的位置上调,能看到切换的按钮)

猜你喜欢

转载自blog.csdn.net/qq_40513881/article/details/84142675