- cnpm install --save vue-i18n
- 在main.js中添加
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh-CN', // 语言标识
// this.$i18n.locale // 通过切换locale的值来实现语言切换
messages: {
'zh-CN': require('./components/common/lang/zh'), // 中文语言包
'en-US': require('./components/common/lang/en') // 英文语言包
}
})
new Vue({
el: '#app',
i18n,
router,
components: {
App
},
template: '<App/>'
})
- 新建翻译文件zh.js en.js
zh.js
export const m = {
music: '音乐',
findMusic: '发现音乐',
Account: '账号',
password: '密码',
login: '登录',
loginInterface: '登录界面',
enterAccount: '请输入账号',
enterPassword: '请输入密码'
}
en.js
export const m = {
music: 'Music', // 音乐
findMusic: 'FIND MUSIC', // 发现音乐
Account: 'Account',
password: 'Password',
login: 'Login',
loginInterface: 'Login Interface',
enterAccount: 'Please enter your account number',
enterPassword: 'Please input a password'
}
- 使用
<template>
<div class="login-container">
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="login_box">
<h1 class="title">{{$t('m.loginInterface')}}</h1>
<el-form-item prop="Account">
<el-input type="text" v-model="ruleForm.Account" :placeholder="$t('m.Account')" autocomplete="off"></el-input>
</el-form-item>
<el-form-item prop="Pass">
<el-input type="password" v-model="ruleForm.Pass" :placeholder="$t('m.password')" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')" class="login_btn">{{$t('m.login')}}</el-button>
</el-form-item>
<el-row class="btnGroup">
<el-button @click="lang('zh-CN')" :type="this.$i18n.locale === 'zh-CN' ? 'success' : ''" size="mini">中文</el-button>
<el-button @click="lang('en-US')" :type="this.$i18n.locale === 'en-US' ? 'success' : ''" size="mini">English</el-button>
</el-row>
</el-form>
</div>
</template>
<script>
export default {
data () {
var validateAccount = (rule, value, callback) => {
if (value === '') {
callback(new Error(this.$t('m.enterAccount')))
} else {
callback()
}
}
var validatePass = (rule, value, callback) => {
if (value === '') {
callback(new Error(this.$t('m.enterPassword')))
} else {
callback()
}
}
}
}
</script>