1、安装i18n
npm install vue-i18n -S
安装版本 8.26.5, 9.2.2亲测项目报错
2、main.js
// 引入 lang/index.js
import i18n from './lang/index.js'
// 挂载
new Vue({
i18n,
router,
store,
render: h => h(App)
}).$mount('#app')
3、lang/index.js
// 引入vue-i18n
import VueI18n from 'vue-i18n'
import Vue from 'vue'
// 引入语言包
import en from './en.js'
import zh from './zh.js'
// 注册
Vue.use(VueI18n)
// 语言包
const messages = {
en,
zh
}
const i18n = new VueI18n({
local: localStorage.getItem('lang') || 'zh', // 语言标识,通过切换locale的值来实现语言切换
messages
})
export default i18n;
4、lang/zh.js & lang/en.js
// zh.js
export default {
lang: {
title: '标题'
}
}
// en.js
export default {
lang: {
title: 'Title'
}
}
5、使用
// html
{{ $t("lang.title") }}
<input :placeholder="$t(lang.title)" maxlength="24">
// js
this.$t('lang.title');
6、切换
<button @click="lang_change('zh')">中文</button>
<button @click="lang_change('en')">英文</button>
methods:{
lang_change(value){
if(value === 'zh'){
this.$i18n.locale = "zh";
localStorage.setItem('lang', 'zh') // 存储local值
}else{
this.$i18n.locale = "en";
localStorage.setItem('lang', 'en')
}
}
}