vue切换国际化vue-i18n的使用

163 阅读1分钟

安装

1.CDN安装

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>

2.npm安装

npm install vue-i18n

3.cnpm安装

cnpm install vue-i18n

4.yarn安装

yarn add vue-i18n

以上根据实际情况选择安装

使用

1.在main.js中引入vue-i18n

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

//可以把需要显示的语言保存在浏览器中
var lang = localStorage.getItem('lang')
//第一次进入页面判断是否存在,不存在给个默认值,存在就赋值
lang ? lang : lang = 'cn'

const i18n = new VueI18n({
    locale: lang,
    messages: {
        //导入需要的语言包
        'cn': require('./js/i18n/cn'), // 中文语言包
        'en': require('./js/i18n/en'), // 英文语言包
    },
    silentTranslationWarn: true,//加上这个是为了隐藏浏览器控制台上的警告
})

new Vue({
    el: '#app',
    router,
    i18n,//把vue-i18n挂载在vue实例中
    components: { App },
    template: '<App/>'
})

2.创建需要的语言包,cn.js和en.js

cn.js文件夹

export const lang = {
    index: {
        home:'首页'
    }
}

en.js文件夹

export const lang = {
    index: {
        home:'index'
    }
}

3.在组件中使用

在组件index.vue中使用

<template>
    <div>
        标签内使用
        <div>{{$t('lang.index.home')}}<div>
        <div v-text="$t('lang.index.home')"><div>
        <div>{{msg}}<div>
        <button type="button" @click="setLang" v-if="isShow">切换英文</button>
        <button type="button" @click="setLang" v-else>切换中文</button>
    <div>
</template>
<script>
export default {
  data() {
    return {
      msg:this.$t('lang.index.home'),//js中使用
      isShow:'true'
    };
  },
  methods: {
    setLang(){
        //做了个判断,isShow等于true就切换英文,false切换中文
        if(this.isShow){
            this.isShow=false
            this.$i18n.locale='en',//this.$i18n.locale是切换语言的关键语法
            localStorage.setItem('lang','en');
            this.msg=this.$t('lang.index.home')
        }else{
            this.isShow=true
            this.$i18n.locale='cn',
            localStorage.setItem('lang','cn');
            this.msg=this.$t('lang.index.home')
        }
    } 
  }
};
</script>

因为在js中使用不会立即切换,所以我重新赋值了,不过官方推荐使用computed

可以查看官方文档

kazupon.github.io/vue-i18n/zh…