vue3+ts使用vue-i18n
1、安装插件
npm install --save vue-i18n
yarn add vue-i18n
2、配置文件
locale/index.ts
import { createI18n } from 'vue-i18n'
import zhCN from './lang/zh-CN'
import enUS from './lang/en-US'
export const LOCALE_OPTIONS = [
{ label: '中文', value: 'zh-CN' },
{ label: 'English', value: 'en-US' },
];
const defaultLocale = localStorage.getItem('locale') || 'zh-CN';
const i18n = createI18n({
locale: defaultLocale,
legacy: false, // 解决控制台报错 Uncaught SyntaxError: Not available in legacy mode
messages: {
'zh-CN': zhCN,
'en-US': enUS,
}
})
export default i18n
locale/lang/zh-CN.ts
export default {
'menu.list': '列表',
'menu.message': '信息',
}
locale/lang/en-US.ts
export default {
'menu.list': 'List',
'menu.message': 'Message'
}
3、在main.ts
引入
main.ts
import i18n from './locale'
// 在app.mount之前
app.use(i18n)
4、在页面中使用
<template>
<div>
<ul>
<li
v-for="(item, index) in locales"
:key="index"
@click="changeLocale(item.value)"
>{{ item.label }}</li>
</ul>
<p>{{ $t('menu.list') }}</p>
<p>{{ $t('menu.message') }}</p>
<p></p>
</div>
</template>
<script setup lang="ts">
import { LOCALE_OPTIONS } from '@/locale'
import { useI18n } from 'vue-i18n'
const locales = [
...LOCALE_OPTIONS
]
const i18n = useI18n()
function changeLocale(value: string) {
i18n.locale.value = value;
localStorage.setItem('locale', value)
}
</script>
5、解决控制台报错/警告
5.1、需要配置全局变量
- 警告信息
You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.
- 解决方案
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
chainWebpack: (config) => {
config.resolve.alias
.set('vue-i18n', 'vue-i18n/dist/vue-i18n.cjs.js')
},
})
5.2、遗留模式报错
- 报错信息
Uncaught SyntaxError: Not available in legacy mode
- 解决方案
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
...
legacy: false, // 解决控制台报错 Uncaught SyntaxError: Not available in legacy mode
...
})