执行以下命令安装vue 国际化插件vue-i18n
npm install vue-i18n --save
执行以下命令安装 js-cookie
npm install js-cookie --save
在src目录下 新建lang文件夹 在lang文件夹下存放 语言脚本 如下:
en.js
export default {
// 导航栏
linkArr: [
{content: 'Homepage', id: 'HomePage'},
{content: 'Product', id: 'Product'},
{content: 'information', id: 'InforMation'},
{content: 'AboutUs', id: 'About'},
{content: 'JoinUs', id: 'Join'}
// {content: 'English', id: 'English'}
]
}
zh.js
export default {
// 导航栏
linkArr: [
{content: '首页', id: 'HomePage'},
{content: '产品', id: 'Product'},
{content: '资讯', id: 'InforMation'},
{content: '关于我们', id: 'About'},
{content: '加入我们', id: 'Join'}
// {content: 'English', id: 'English'}
]
}
index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'
// import locale from 'element-ui/lib/locale';
import elementEnLocale from 'element-ui/lib/locale/lang/en' // element-ui lang
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'// element-ui lang
import enLocale from './en'
import zhLocale from './zh'
Vue.use(VueI18n);
const messages = {
en: {
...enLocale,
...elementEnLocale
},
zh: {
...zhLocale,
...elementZhLocale
}
};
const i18n = new VueI18n({
locale: Cookies.get('language') || 'en',
messages
})
export default i18n
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import i18n from './lang'
Vue.use(ElementUI, {
size: 'medium',
i18n: (key, value) => i18n.t(key, value)
});
new Vue({
router,
store,
i18n,
render: h => h(App)
}).$mount("#app");
xxx.vue
<template>
<ul>
<router-link :to="{path: '/' + item.id}" v-for="(item,index) in $t('linkArr')" :key="index">
<div class="line" v-if="5===index"></div>
</router-link>
<li @click="liClick1">
<span>English</span>
</li>
</ul>
</template>
methods: {
liClick1() {
if (this.$i18n.locale === 'zh') {
this.$i18n.locale = 'en';
// 将新语言保存到全局状态管理
this.$store.dispatch('update_current_lang', 'en');
cookie.set('language', 'en');
}else {
this.$i18n.locale = 'zh';
// 将新语言保存到全局状态管理
this.$store.dispatch('update_current_lang', 'zh');
cookie.set('language', 'zh');
}
}
}