https://kazupon.github.io/vue-i18n/zh/introduction.html
1 先安装 npm i vue-i18n -S
2 在src目录下面创建i18n文件夹
en.js文件放置英文标题
module.exports = {
message: {
title: 'english'
}
}
zh.js文件放置中文标题
export default {
message: {
title: '中文'
}
}
在i18n.js文件放置
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import zh from './langs/zh'
import en from './langs/en'
Vue.use(VueI18n)
const messages = {
zh,
en
}
const i18n = new VueI18n({
locale: localStorage.getItem('locale') || 'zh', // 语言标识
messages
})
export default i18n
在main.js文件中导入i18n
import i18n from './i18n/i18n'
new Vue({
render: h => h(App),
i18n
}).$mount('#app')
主页面
<template>
<div>
<h1>{{ $t("message.title") }}</h1>
<el-button type="primary" @click="handleClick">点击切换语言</el-button>
</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
handleClick () {
this.$i18n.locale = (this.$i18n.locale === 'zh' ? 'en' : 'zh')
localStorage.setItem('locale', this.$i18n.locale)
}
}
}
</script>
- 在各个页面使用插值语法{{ $t标题 }} 就可以直接显示对应的中英文