当面向不同语言群体的用户时,我们就需要考虑前端页面的语言切换问题,在vue中,可以通过vue-i18n插件实现。
1、安装vue-i18n
npm install vue-i18n --save-dev
2、新建语言配置js文件,我的文件目录是/src/config/lang。
lang目录下我建了两个文件,en.js和zh.js,分别表示英文语言文件和中文语言文件,文件内容如下。
en.js
module.exports = {
btn: {
lang: '中文',
test: 'click'
},
content: {
textarea: 'Welcome to my website!',
input: 'This is a test'
}
}
zh.js
module.exports = {
btn: {
lang: 'English',
test: '点击'
},
content: {
textarea: '欢迎访问我的主页!',
input: '测试内容'
}
}
3、在main.js中引入vue-i18n
4、在具体页面中引用
在页面中引用主要有两种方式
(1)在<template>中引用
<el-button type="text" @click="langChange">{{$t('btn.lang')}}</el-button>
<el-input
type="textarea"
:rows="6"
:placeholder="$t('content.textarea')"
v-model="content">
</el-input>
(2)在js中引用
this.input = this.$t('content.input')
5、语言切换可以在页面设置一个按钮,按钮的触发事件如下
if (this.$i18n.locale === 'en') {
this.$i18n.locale = 'zh'
} else {
this.$i18n.locale = 'en'
}
根据以上基本内容,我写了一个简单的页面程序,在页面中点击文字按钮触发语言切换功能,页面中相应的文字语言改变。还有一个测试按钮是为了测试在js中的调用,点击测试按钮后,让输入框的值改变为语言库中的对应值。
<template>
<div class="lang">
<div class="flexBox">
<el-button type="text" @click="langChange">{{$t('btn.lang')}}</el-button>
</div>
<div class="inputDiv1">
<el-input
type="textarea"
:rows="6"
:placeholder="$t('content.textarea')"
v-model="content">
</el-input>
</div>
<el-button type="primary" plain class="btn" @click="test">{{$t('btn.test')}}</el-button>
<div class="inputDiv2">
<el-input v-model="input"></el-input>
</div>
</div>
</template>
<script>
export default {
data () {
return {
content: '',
input: ''
}
},
mounted: function () {
},
methods: {
langChange: function () {
if (this.$i18n.locale === 'en') {
this.$i18n.locale = 'zh'
} else {
this.$i18n.locale = 'en'
}
this.input = ''
},
test: function () {
this.input = this.$t('content.input')
}
}
}
</script>
<style scoped>
.lang {
min-height: 100vh;
}
.inputDiv1 {
margin: 20px 0 0 50px;
width: 30%;
}
.inputDiv2 {
margin: 20px 0 0 50px;
width: 20%;
}
.btn {
float: left;
margin: 30px 50px;
}
.flexBox {
float: left;
padding: 50px 0 0 50px;
}
</style>
页面切换效果如下
英文状态下
中文状态下