1.安装
如果是vue2直接安装8.2.1版本,否则会出现版本不匹配的错误
npm install vue- i18n@8.2 .1 -- save
2.文件编辑
在src目录下创建文件
en.js
export const h = { system : "Background management system" , loginOut : "LoginOut" , LayoutSet : 'Layout settings' , LanguageSwitch : 'Language switching' , PersonalCenter : 'Personal Center' , homePage : 'Home Page'
}
zh.js
export const h = { system : "后台管理" , loginOut : "退出登录" , LayoutSet : '布局设置' , LanguageSwitch : '语言切换' , PersonalCenter : '个人中心' , homePage : '首页'
}
index.js
import Vue from "vue" ;
import VueI18n from "vue-i18n" ;
import ElementLocale from 'element-ui/lib/locale'
import zhLocale from "element-ui/lib/locale/lang/zh-CN"
import enLocale from "element-ui/lib/locale/lang/en"
const zh= require ( "./lan/zh" )
const en = require ( "./lan/en" )
Vue. use ( VueI18n) ;
export const i18n = new VueI18n ( { locale : localStorage. getItem ( "lang" ) || "zh" , messages : { zh : { ... zh, ... zhLocale} , en : { ... en, ... enLocale} }
} )
ElementLocale. i18n ( ( key, value ) => i18n. t ( key, value) )
export const translate = ( localeKey ) => { const locale = localStorage. getItem ( "lang" ) || "zh" const hasKey = i18n. te ( localeKey, locale) const translatedStr = i18n. t ( localeKey) if ( hasKey) { return translatedStr} return localeKey
} export default i18n;
main.js
import { i18n } from './i18n/index' new Vue ( { el : '#app' , i18n, router, store, render : h => h ( App)
} )
router.js
import { translate as $t } from "@/i18n"