vue实现国际化,vue-i18n的使用,页面多语言切换

安装插件

$ cnpm i vue-i18n -S

main.js 引入

import Vue from 'vue'
import VueI18n from 'vue-i18n' // 引入
Vue.use(VueI18n)
// 创建实例
const i18n = new VueI18n({
    
    
    locale: 'zh', // 语言标识
    messages: {
    
    
        'zh': require('./assets/lang/zh.js'), 
        'en': require('./assets/lang/en.js')
    }
})

// 挂载vue 实例
new Vue({
    
    
    router,
    i18n,
    store,
    render: h => h(App)
}).$mount('#app')

// 其余页面 用 this.$t('') 来代替之前的文字即可实现国际化。

vue-i18n挂载到实例上 会在全局的this上也会挂载相应的对象和方法
this.$t(‘key’) =》 对应的是不同语言包相同的key值

this.$i18n.locale 代表当前的语言主题 可以判断赋值
如下demo vue文件

<template>
  <div id="app">
    <p>{
    
    {
    
    this.$t('apple')}}</p>
   <button @click="switchLang">{
    
    {
    
    this.$t('switch')}}</button>
  </div>
</template>

<script>

export default {
    
    
  name: 'App',
  components: {
    
    
  },
  methods: {
    
    
    switchLang() {
    
    
      if ( this.$i18n.locale === "zh") {
    
    
        this.$i18n.locale = "en"
      } else {
    
    
        this.$i18n.locale = "zh"
      }
    }
    
  }
}
</script>

<style>
#app {
    
    
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

elementUI增加国际化

Vue.use(ElementUI, {
    
    
  i18n: (key, value) => i18n.t(key, value) // 在注册Element时设置i18n的处理方法 给分页器增加国际化
})

然后去语言包里增加相应的中英版本

el:{
    
    
      pagination:{
    
    
      goto:'前往',
      pagesize:'条/页',
      total:'共{total}条',
      pageClassifier:'页'
      }
},

main.js 里写入

// 自己写的语言包
import zhLocal from './assets/lang/zh.js'
import enLocal from './assets/lang/en.js'
// elemet自带的语言包
import elementZhLocal from 'element-ui/lib/locale/lang/zh-CN'
import elementEnLocal from 'element-ui/lib/locale/lang/en'

const i18n = new VueI18n({
    
    
    locale: 'zh', // 语言标识
    messages: {
    
    
        'zh': {
    
    
          ...zhLocal,
          ...elementZhLocal
        },
        'en': {
    
    
          ...enLocal,
          ...elementEnLocal
        }
    }
});

猜你喜欢

转载自blog.csdn.net/weixin_45131389/article/details/115289100