国际化基础应用

1.安装

yarn add vue-i18n

2.创建js并导入

import Vuei18n from 'vue-i18n'

3.实例化

import Vue from 'vue'
Vue.use(Vuei18n)

4.定义

const i18n = new Vuei18n({
     locale:'en',
     messages:{
         en:{
             xxxx:'hello'
         },
         zh:{
             xxxx:'你好'
         }
     }
})

5.暴露出去

export default i18n

6..main.js中导入

import i18n from '@/lang/index'

7.挂载

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

8.使用

<template>
  <div>首页
    {
   
   { $t('xxx') }}
    <button @click="fnclick">按钮</button>
  </div>
</template>
<script>
export default {
  methods: {
    fnclick() {
      const a = ['en', 'zh']
      const b = a.indexOf(this.$i18n.locale)
      this.$i18n.locale = a[1 - b]
      this.$router.go(0)
    }
  }
}
</script>

element-ul中使用

1.找到main.js

// 如果想要中文版 element-ui,按如下方式声明
// 默认Vue.use(ElementUI)


// 修改
Vue.use(ElementUI, {
  i18n: (key, value) => i18n.t(key, value)
})

2.定义国际化的js文件中

import elemEn from 'element-ui/lib/locale/lang/en'
import elemzh from 'element-ui/lib/locale/lang/zh-CN'


const i18n = new Vuei18n({
  locale:'en',
  messages: {
    en: {
      xxx: 'hello',
      ...elemEn,
    },
    zh: {
      xxx: '你好',
      ...elemzh,
    }
  }
})

export default i18n

3.避免刷新页面丢失国际化效果.

1.安装
yarn add js-cookie
2.导入
import cookiejs from 'js-cookie'
3.使用
cookiejs.get 存
cookiejs.set 取
cookiejs.remove 删

备注:

如果不想体验太差.可以把刷新当前页面.改为静默刷新的方式处理.. 

Guess you like

Origin blog.csdn.net/wangyangzxc123/article/details/121575086