• 微信号
  • 微信号
您当前的位置:首页 > 学海无涯 > 茑语花香>vue-cli3实战-- 结合element-ui和vant框架实现国际化多语言切换

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

孤峰 孤峰家 2023-08-08 150人阅读

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

今天介绍的这个就是开源的 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切换语言的方法(一个练习中英文切换的**,更多语言请自行配置)

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);}

}

在**in.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 = Localsnew 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><**></**><!-- vant组件 --><van-datetime-pickerv-model="currentDate"type="datetime":min-date="minDate":**x-date="**xDate" 

/></div>

</template><script>

import ** from './home-**'

export default {name: 'HelloWorld',props: {msg: String},data(){return{minHour: 10,**xHour: 20,minDate: new Date(),**xDate: 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:{**}

}

</script>

一起看下结果

中文:

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

转载:感谢您阅览,转载请注明文章出处“来源从小爱孤峰知识网:一个分享知识和生活随笔记录的知识小站”。

链接:vue-cli3实战-- 结合element-ui和vant框架实现国际化多语言切换http://www.gufeng7.com/niaolang/1816.html

联系:如果侵犯了你的权益请来信告知我们删除。邮箱:119882116@qq.com

标签: