1.安装插件:npm install vue-i18n --save
2.src下新建i18n文件夹,
i18n文件夹下创建langs文件夹和i18n.js文件
langs文件夹下创建cn.js; en.js; index.js
如图:
3. i18n.js:
import Vue from "vue"; import locale from 'element-ui/lib/locale' import VueI18n from "vue-i18n"; import messages from "./langs"; Vue.use(VueI18n); const i18n = new VueI18n({ locale: localStorage.lang || "cn", messages }); locale.i18n((key, value) => i18n.t(key, value)) export default i18n;
4. cn.js:
import zhLocale from "element-ui/lib/locale/lang/zh-CN"; const cn = { message: { login: "登录", password: "密码不可为空", upassword: "密码", uname: "账户", }, ...zhLocale }; export default cn;
5. en.js:
import enLocale from 'element-ui/lib/locale/lang/en' const en = { message: { login: "Login", password: "Password is required", upassword: "password", uname: "account" }, ...enLocale }; export default en;
6.index.js:
import en from "./en"; import cn from "./cn"; export default { en, cn };
7. main.js:
import Vue from 'vue' import App from './App' import store from './store' import i18n from './i18n/i18n' Vue.config.productionTip = false window.app = new Vue({ store, i18n, render: h => h(App) }).$mount('#app')
以上就是配置好了,可以使用了
8. 使用:
//data()中声明 data() { return { lang: "", }; },
//作为文本内容,绑定在标签中 <div class="manage_tip"> <span class="title">{{$t('message.login')}}</span> </div>
//作为属性绑定 <el-form-item :label="$t('message.uname')" prop="pnone"> <el-input v-model="loginUser.pnone" placeholder="请输入手机或邮箱"></el-input> </el-form-item>
//作为elementui 中的校验规则,要放在computed中 computed: { rules() { return { password: [ { required: true, message: this.$t("message.password"), trigger: "blur" }, { pattern: /^(?=.*d)(?=.*[a-zA-Z])(?=.*[W_]).{6,16}$/, message: "输入6-16位包含数字、字母、特殊字符的密码", trigger: "blur" } ], }; } },
//切换中英文 <el-dropdown @command="handleCommand"> <span class="el-dropdown-link"> 中英文切换 <i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item command="cn">中文</el-dropdown-item> <el-dropdown-item command="en">英文</el-dropdown-item> </el-dropdown-menu> </el-dropdown> //切换语言的事件 methods: { // 根据下拉框的中被选中的值切换语言 handleCommand(command) { // this.$message("click on item " + command); switch (command) { case "cn": { this.lang = "cn"; this.$i18n.locale = this.lang; break; } case "en": { this.lang = "en"; this.$i18n.locale = this.lang; break; } default: break; } }, }