Vue 中英文切换(vue-i18n)结合elementUI

项目中需要用到中英文切换,这里用到vue-i18n插件,配合localStorage使用
第一步:下载包 vue-i18n
npm install --save vue-i18n
第二步:在main.js中引入 vue-i18n
import VueI18n from "vue-i18n";
Vue.use(VueI18n)
// Create VueI18n instance with options
const i18n = new VueI18n({
          
   
  locale: localStorage.getItem(locale) || cn, // 语言标识
  messages:  {
          
   
	  en: {
          
   
	    message: hello,
	    ...enLocale
	  },
	  cn: {
          
   
	    message: 你好,
	    ...zhLocale
	  }
}, // set locale messages  语言包
  silentTranslationWarn: true
})
Vue.use(Element, {
          
   
  i18n: (key, value) => i18n.t(key, value)
})
new Vue({
          
   
  router,
  store,
  i18n,
  render: h => h(App)
}).$mount(#app)
第三步:在i18n文件夹的en.js/zh-CN.js文件中配置中英文
第四步:在.vue文件中使用 vue-i18n$t(title)
<span class="pageTitle">{
         
  {$t($route.meta.title)}}</span>
<span class="pageTitle">{
         
  {$t(title)}}</span>
第五步: 语言切换 方法
/** 语言切换*/
 toggleLang(lang) {
          
   
   localStorage.setItem(locale, lang)  // 设置 localStorage
   this.$i18n.locale = localStorage.getItem(locale)  // 设置 locale
 },
第六步: 使用watch监听当前语言 this.$i18n.locale

当前语言类型变化时,重新请求接口

watch: {
          
   
    $i18n.locale(newType) {
          
   
        this.getList(newType)
    }
},
经验分享 程序员 微信小程序 职场和发展