一、i18n的安装

这个地方要注意自己的vue版本和i1n8的匹配程度,如果是vue2点几,记得安装i18n的@8版本,不然会自动安装的最新版本,后面会报错哦,查询了下资料,好像最新版本是适配的vue3。

npm install vue-i18n@8 --save

二、新建i18n相关文件夹及文件

在src下面新建i18n文件夹,然后在里面新建index.js,里面的内容如下

import Vue from 'vue';

import VueI18n from 'vue-i18n';

import locale from 'element-ui/lib/locale';

Vue.use(VueI18n);

// 引入自定义的各个语言配置文件

import zh from './config/zh';

import en from './config/en';

//element-ui自带多语言配置

import zhLocale from 'element-ui/lib/locale/lang/zh-CN';

import enLocale from 'element-ui/lib/locale/lang/en';

const messages = {

en: {

...en,

...enLocale

},

zh: {

...zh,

...zhLocale

},

}

// 创建vue-i18n实例i18n

const i18n = new VueI18n({

// 设置默认语言

locale: localStorage.getItem('locale') || 'zh', // 语言标识,页面对应显示相同的语言

// 添加多语言(每一个语言标示对应一个语言文件)

messages:messages,

})

// 非 vue 文件中使用这个方法

const translate = (localeKey) => {

const locale = localStorage.getItem("language") || "zh"

const hasKey = i18n.te(localeKey, locale) // 使用i18n的 te 方法来检查是否能够匹配到对应键值

const translatedStr = i18n.t(localeKey)

if (hasKey) {

return translatedStr

}

return localeKey

}

locale.i18n((key, value) => i18n.t(key, value)) //为了实现element插件的多语言切换

// 暴露i18n

export {

i18n,

translate

};

新建i18n文件夹里面新建config文件夹,然后在里面新建en.js和zh.js

en.js代码

const en = {

login:{

title:'I am the title',

}

}

export default en;

zh.js代码

const zh = {

login:{

title:'我是标题',

}

}

export default zh;

三、在main.js引入

主要是引入以后要在new Vue的地方加入 i18n,

import {i18n} from './i18n/index.js';

new Vue({

el: '#app',

i18n,

router,

store,

mounted() {

window.isfitVue = this;

},

components: { App },

template: ''

})

四、功能切换

五、在vue文件里面的使用

在template中直接使用

{{$t("login.title")}}

//或者

在script中加上this就行

this.$t('login.title'),

六、在单独的js文件中使用

//导入 ,这里的路径自己找一下自己的文件路径

import { translate as $t } from "../../../../../i18n/index.js"

//使用

name: $t('login.title'),

七、如果需要在js文件中获取当前保存的状态,也就是this.$i18n.locale

//导入,记得切换自己的路径

import { i18n } from "../i18n/index.js"

//使用

console.log(i18n.locale)

if(i18n.locale=='en'){

}

八、写在最后

这里面基本都是我使用的时候遇到问题单独去查的资料,但是都写得比较分散,比如我遇到了最开始的安装问题,或者遇到了在js里面使用的问题,又需要去单独的查资料说怎么使用的问题,所以想着说把自己遇到的问题都写成一个合集,希望能帮助到更多跟我一样的小伙伴,最后,如果有帮到您记得留言或点赞哦,会觉得很开心,觉得自己帮助到了人~~

推荐阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: