多语言切换vue2+vue-i18n

环境:vue: 2.6.10,vue-i18n: 8.28.2

安装插件

npm install vue-i18n@8

在package.json中检查

 

 在main.js中引入

import VueI18n from 'vue-i18n';
Vue.use(VueI18n);

const i18n = new VueI18n({
  locale: localStorage.getItem('lang') || 'zh', // 语言标识 //this.$i18n.locale // 通过切换locale的值来实现语言切换
  messages: {
     'zh': require('@/assets/VueI18n/language-zh'), 
     'en': require('@/assets/VueI18n/language-en'),
     'fn': require('@/assets/VueI18n/language-fn')
  }
})

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

  assets/VueI18n/language-en.js中定义对应几种语言的展示内容,每个文件变量名需要一样

module.exports =  {
  langage:{
    ch:"CH",
    en:"EN",
    fn:"FN"
  },
  login: {
    title:"Login",
    message: "Welcome Sign In",
  }
.....几个语言就几个js
}

 

使用

几个切换语言的按钮

 <div class="langages">
      <span @click="changeLaguageZhEnFn('zh')">{{$t('langage.ch')}}</span>
      <span @click="changeLaguageZhEnFn('en')">{{$t('langage.en')}}</span>
      <span @click="changeLaguageZhEnFn('fn')">{{$t('langage.fn')}}</span>
    </div>
  changeLaguageZhEnFn(lang) {
      this.$i18n.locale = lang;
      this.lang = lang;
    },

  

其他的文字展示

<div class="title-container">
<h3 class="title">{{$t("login.title")}}</h3>
</div>
<input :placeholder="$t(login.username)" maxlength="24">

 

防止当页面刷新 语言切换成初始状态 需要

localStorage.setItem('lang',"zh");

 

https://kazupon.github.io/vue-i18n/

posted @ 2022-12-21 14:46  明媚下雨天  阅读(953)  评论(0)    收藏  举报