1. 安装 vue-i18n依赖包
首先在自己的项目中安装 vue-i18n依赖包
npm install vue-i18n --save-dev
2. 在src目录下创建lang目录
lang目录:
lang > index.js
lang > en.js
lang > zh.js
index.js代码如下:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import enLocale from './en'
import zhLocale from './zh'
import elementEnLocale from 'element-ui/lib/locale/lang/en'
import elementZHLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh', //默认语言
messages: {
en: {
...enLocale,
...elementEnLocale
},
zh: {
...zhLocale,
...elementZHLocale
}
}
})
export default i18n
en.js是英文语言包文件
export default {
login: {
login_1: 'Username',
login_2: 'Password',
login_3: 'Please input a user name',
login_4: 'Please input a password',
login_5: 'Sign In',
login_6: 'Success',
},
register: {
register_9: 'Mobile',
register_11: 'Mobile verification code',
register_13: 'Email',
register_22: 'Register now',
},
}
zh.js是中文语言包文件
export default {
login: {
login_1: '用户名',
login_2: '密码',
login_3: '请输入用户名',
login_4: '请输入密码',
login_5: '登录',
login_6: '成功',
},
register: {
register_1: '手机号',
register_2: '手机验证码',
register_3: '邮箱',
register_4: '立即注册',
},
}
3. 在main.js中引入
import i18n from './lang/index'
Vue.use(ElementUI, {
i18n: (key, value) => i18n.t(key, value)
})
new Vue({
router,
i18n,
render: h => h(App)
}).$mount('#app')
4. 在组件中调用
(1)template模板
<el-form :model="loginForm" :rules="loginRule" ref="loginForm">
<el-form-item prop="userName">
<el-input type="text" v-model.trim="loginForm.userName" :placeholder="$t('login.login_1')" maxlength="64"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" v-model.trim="loginForm.password" :placeholder="$t('login.login_2')" @keyup.enter.native="loginSubmit" maxlength="64"></el-input>
</el-form-item>
<el-form-item>
<el-button class="login-button" type="primary" @click="loginSubmit">{{ $t('login.login_5') }}</el-button>
</el-form-item>
</el-form>
(2)script代码部分
<script>
export default {
data() {
return {
loginForm: {
userName: '',
password: '',
},
loginRule: {
userName: [
{ required: true, message: `${this.$t('login.login_3')}`, trigger: 'blur' },
],
password: [
{ required: true, message: `${this.$t('login.login_4')}`, trigger: 'blur' },
],
}
}
},
methods: {
//登录
loginSubmit() {
this.$refs.loginForm.validate((valid) => {
if (valid) {
console.log(`${this.$t('login.login_6')}`);
} else {
return false;
}
});
},
},
mounted() {
console.log(`${this.$t('login.login_6')}`);
}
}
</script>
(3)在公共过滤器filter.js中调用
import i18n from './../../lang/index'
//账号类型
exports.accountTypeFilter = (value) => {
if (value == 1) {
return i18n.t('register.register_1');
} else if (value == 2) {
return i18n.t('register.register_3');
};
};