1. 安装
npm install vue-i18n -s
2. 引入main.js
import { createI18n } from 'vue-i18n'
import messages from './i18n/index'
const i18n = createI18n({
legacy: false,
locale: Cookies.get('language') || 'en_us', // set locale
fallbackLocale: 'en_us', // set fallback locale
messages: messages
})
app.use(i18n)
3. 新建文件index.js
import en_us from "@/i18n/en_us.js";
import zh_cn from "@/i18n/zh_cn.js";
export default {
en_us,
zh_cn
}
4. 新建文件en_us.js
export default {
login: {
username: 'username'
}
}
5. 新建文件zh_cn.js
export default {
login: {
username: '用户名'
}
}
6. 使用
<script>
import {useI18n} from "vue-i18n";
const {t} = useI18n()
const data = ref({
rules: {
label: [{required: true, message: t('login.username'), trigger: "blur"}],
value: [{required: true, message: t('login.username'), trigger: "blur"}]
}
});
</script>
<template>
<div>
{{ t('login.username') }}
</div>
</template>
7. 语言切换
<script>
import {useI18n} from 'vue-i18n'
import Cookies from "js-cookie";
const {t, locale} = useI18n()
const handleSetLanguage = (language) => {
Cookies.set('language', language)
locale.value = language;
}
</script>
<template>
<div>
<el-dropdown @command="handleSetLanguage">
// 这里去 阿里巴巴矢量图标库 找个图贴一下就行
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item :command="'en_us'">English</el-dropdown-item>
<el-dropdown-item :command="'zh_cn'">简体中文</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
</div>
</template>
8. 样式
iconfont-阿里巴巴矢量图标库