Vue双语言切换
一、下载依赖
npm install vue-i18n –save
二、文件目录
assets
├── lang
├── ├──zh-CN.js
├── ├──en.js
//zh-CN.js
module.exports = {
lang:{
helloworld:'你好世界'
}
}
//en.js
module.exports = {
lang:{
helloworld:'helloworld'
}
}
三、在main.js中配置
//main.js
import Vue from 'vue'
import Vuei18n from 'vue-i18n'
Vue.use(Vuei18n)
const i18n = new Vuei18n({
locale:'zh-CN',
messages:{
'zh-CN':require('./assets/lang/zh-CN'),
'en':require('./assets/lang/en')
}
})
const app = new Vue({
router,
i18n,
...App
}).$mount('#app')
四、组件中使用
<template>
<div>
<h1>{{$t('lang.helloworld')}}</h1>
<button @click='change'>中英文切换</button>
</div>
</template>
<script>
export default{
data(){
return{
}
},
methods:{
change(){
this.$i18n.locale=this.$i18n.locale=='en'?'zh-CN':'en'
}
}
}
</scipt>