文件目录:
i18n.js:
import Vue from 'vue' import VueI18n from 'vue-i18n' import en from './lang/en' import cn from './lang/cn' import enLocale from 'element-ui/lib/locale/lang/en' import zhLocale from 'element-ui/lib/locale/lang/zh-CN' Vue.use(VueI18n) const messages = { en: { ...en, ...enLocale }, zh: { ...cn, ...zhLocale // 或者用 Object.assign({ message: '你好' }, zhLocale) } } const i18n = new VueI18n({ locale: 'en', // 设置默认语言 messages }) export default i18n
cn.js:
const cn = { message: { i1: '欢迎来到我的项目', }, } export default cn
en.js:
const en = { message: { i1: 'Welcome to my project', }, } export default en;
main.js:
import i18n from './components/i18n/i18n.js'; Vue.use(ElementUI,{ i18n: (key, value) => i18n.t(key, value) }); new Vue({ el: '#app', router, store, i18n, components: { App }, template: '<App/>' })
使用:
<template> <div class="hello"> <el-button type="primary" @click="switchChinese()">切换中文</el-button> <el-button type="primary" @click="switchEnlish()">切换英文</el-button> <p>{{ $t("message.i1") }}</p> <el-date-picker v-model="value1" type="date" placeholder="选择日期"> </el-date-picker> </div> </template> <script> export default { name: "HelloWorld", data() { return {value1: '',}; }, methods: { switchChinese() { this.$i18n.locale = "zh"; }, switchEnlish() { this.$i18n.locale = "en"; }, }, }; </script>
效果: