vue网站多语言设置
2019-05-27 本文已影响0人
散樱乱舞
1.创建
- i18n.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: localStorage.getItem('locale') || 'zh',
messages: {
'zh': require('./langs/zh'),
'en': require('./langs/en')
}
})
export default i18n
- en.js
module.exports = {
language:'english',
nav:{
Home: 'Home',
News:'News'
}
}
- zh.js
module.exports = {
language:'中文',
nav:{
Home: '首页',
News:'新闻资讯'
}
}
- main.js
import i18n from './i18n/i18n'
new Vue({
i18n
}).$mount('#app')
2.使用
- 任意.vue
<div v-text="$t('nav.Home')"></div>
<div v-text="$t('nav.News')"></div>
3.自行切换
- store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
lang: 'zh',
},
mutations: {
swi_lang(state, arg){
state.lang = arg;
}
},
getters: {
get_lang(state){
return state.lang;
}
},
actions: {
}
})
- 任意.vue
<div @click="swi_zh()"></div>
<div @click="swi_en()"></div>
import {mapMutations} from 'vuex'
methods: {
...mapMutations({
swi_lang: 'swi_lang'
}),
swi_zh(){
this.$i18n.locale = 'zh';
this.swi_lang('zh');
},
swi_en(){
this.$i18n.locale = 'en';
this.swi_lang('en');
}
}