1、安装vue-i18n: npm install vue-i18n --save-dev
2、在main.js中添加这些代码
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n(
{
locale: window.localStorage.getItem('language') == null ? "zh" : window.localStorage.getItem('language'), // 语言标识
messages: {
'zh': require('@/assets/lang/zh'),
'en': require('@/assets/lang/en')
}
}
)
new Vue({
el: '#app',
router,
i18n,
components: { App },
template: '<App/>'
})
3、在assets中添加上面得文件夹
module.exports = {
header:{
index:"首页",
project:"项目介绍",
regional:'区位交通',
design:"设计理念",
brand:'品牌服务',
rental:"租赁信息",
footer:"联系我们"
}
}
4、在需要切换得地方使用
<template>
<div class="max" :style="scrollTop>180?'box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);':''">
<div class="header">
<!-- logo -->
<div>
</div>
<!-- <div class="header-logo" @click="changExternal('index')">
<img src="@/assets/header/logo.png" alt="">
</div> -->
<!-- 导航 -->
<div>
<!-- 大屏导航 -->
<ul class="header-ul">
<li class="header-li" :class="external==item.external?'success':''" v-for="(item,index) in list" :key="index"
@click="changExternal(item.external)">
{{$t(item.title)}}
</li>
<li class="header-li"><span :class="language=='zh'?'isColor':''" @click="changeIanguage('zh')">中文</span>/
<span :class="language=='en'?'isColor':''" @click="changeIanguage('en')">EN</span></li>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
name: '',
// 定义属性
data() {
return {
language: window.localStorage.getItem("language") == null ? 'zh' : window.localStorage.getItem("language"),
list: [{
title: "header.index",
external: "index",
},
{
title: "header.project",
external: "project",
},
{
title: "header.regional",
external: "regional",
}, {
title: "header.design",
external: "design",
}, {
title: "header.brand",
external: "brand",
}, {
title: "header.rental",
external: "rental",
}, {
title: "header.footer",
external: "footer",
}
]
}
},
// 方法集合
methods: {
// 改变预言
changeIanguage(language) {
window.localStorage.setItem("language", language)
this.$i18n.locale = language //这个代码负责实时切换语言
}
},
}
</script>
在vue中实现不同语言的切换你学会了吗?