0


vue国际化(多语言)

方法1:用 js-cookie 包 并且挂载在 main.js 上

1、安装 vue-i18n + js-cookie 插件

npm install vue-i18n -S
npm install js-cookie --save

2、去检查一下你安装的 i18n 版本是不是 8.26.5

image.png

3、在 main.js 中引入

import VueI18n from'vue-i18n';import cookie from'js-cookie';

Vue.use(VueI18n);Vue.prototype.cookie = cookie;// 设置 cookie 工具函数Vue.prototype.set_cookie=(name, data, expires)=>{
  cookie.set(name, data,{expires: expires
  })}const i18n ={locale: cookie.get('lang')||'zh',// 语言标识,第一次登录默认是中文messages:{zh:require('@/assets/language/language/local_zh'),// 汉语en:require('@/assets/language/language/local_en'),// 英语}}newVue({el:'#app',
  router,
  i18n,// 把 i18n 挂载在全局上components:{ App },template:'<App/>'})

4、在 src 上建立文件夹

image.png

5、给创建的中文和英文添加语言

注意:二个文件夹的命名要一样

module.exports ={login:{loginhello:"Hello",loginTitle:"Welcome Sign In",}}
module.exports ={login:{loginhello:"你好",loginTitle:"欢迎登录",}}

6、使用

  • html 中使用
{{$t("login.loginhello")}}{{$t('login.loginTitle')}}

在 input 的 placeholder 中使用,其实就是 vue 中的 v-bind
<input :placeholder="$t(login.password)" maxlength="24">
  • js 中使用
this.$t('xxxxx.xxxxx');

7、切换语言

<button @click="lang_change(1)">中文</button><button @click="lang_change(2)">英文</button>
methods:{lang_change(value){if(value==1){this.$i18n.locale ="zh";this.set_cookie('lang','zh',6);// 第一个参数是名字,第二个参数是当前的语言,第三个参数是表示 cookie 过期时间,可能是6(天)}else{this.$i18n.locale ="en";this.set_cookie('lang','en',6);}

方法2:不用 js-cookie 包

1、安装 vue-i18n 插件

npm install vue-i18n -S

2、去检查一下你安装的版本是不是 8.26.5 的

image.png

3、在 src 上建立文件夹

image.png

4、去新建的文件 index.js 里面开工

import Vue from'vue'// 使用插件import VueI18n from'vue-i18n'
Vue.use(VueI18n);const i18n ={locale: localStorage.getItem('lang')||'zh',// 语言标识,第一次登录默认是中文messages:{zh:require('./language/local_zh'),// 中文en:require('./language/local_en'),// 英语......//要多少语言就自己添加多少}}exportdefault i18n

5、去 local_zh.js 和 local_en.js 里填写

注意:二个文件夹的命名要一样

module.exports ={login:{loginhello:"你好",loginTitle:"欢迎登录",}}
module.exports ={login:{loginhello:"Hello",loginTitle:"Welcome Sign In",}}

6、在 main.js 中引入

import i18n from'./assets/language/index.js'// 第一步:引入多语言配置文件index.jsnewVue({el:'#app',
  router,
  i18n,// 第二步:挂载 i18n插件components:{ App },template:'<App/>'})

7、使用

  • html 中使用
{{$t("login.loginhello")}}{{$t('login.loginTitle')}}

在 input 的 placeholder 中使用,其实就是 vue 中的 v-bind
<input :placeholder="$t(login.password)" maxlength="24">
  • js 中使用
this.$t('xxxxx.xxxxx');

8、切换语言

<button@click="lang_change(1)">中文</button><button@click="lang_change(2)">英文</button>
methods:{lang_change(value){if(value==1){this.$i18n.locale ="zh";
      localStorage.setItem('lang',"zh");// 这样保存起来可以防止刷新页面就回到了初始值}else{this.$i18n.locale ="en";
      localStorage.setItem('lang',"en");// 这样保存起来可以防止刷新页面就回到了初始值}

本文转载自: https://blog.csdn.net/m0_54409638/article/details/125181861
版权归原作者 Zhou_慧 所有, 如有侵权,请联系我们删除。

“vue国际化(多语言)”的评论:

还没有评论