npm i vue-i18n@next
我用的是
[email protected]
的,
vue3
的话尽量下载最新版本的插件。
在
src
下新建
local
文件夹,
index
文件下:
import { createI18n } from 'vue-i18n';
import zh_CN from "@/locales/lang/zh_CN";
import en_US from "@/locales/lang/en_US";
import App from './App.vue'
import { createApp } from 'vue'
const options = createI18nOptions();
const i18n = createI18n({
locale,
fallbackLocale: localeMap.zh_CN,
messages: {
zh_CN
en_US
globalInjection: true,
silentTranslationWarn: true,
missingWarn: false,
silentFallbackWarn: true,
legacy: false
createApp(App).use(i18n)
然后直接在main.ts
引入就行了
如果要在组件的script
标签里面引入的话需要加上:
import { useI18n } from "vue-i18n"
const { t } = useI18n()
然后跟$t
一样去使用。
另外当页面刷新的时候国际化就会被初始化,要使用localStorage
来缓存之前用户设置的国际化的值。
如果在vue-i18n
还没加载的时候在ts中使用,会报下面这个错:
SyntaxError: Must be called at the top of a setup function
![在这里插入图片描述](https://img-blog.csdnimg.cn/65fec94b3f5d4394b21407bc39b8aa33.png)
所以要改成这样:
import { i18n } from '@/locales'
const { t } = i18n.global;
而且,每个vue文件如果要在js中使用国际化,都要引入一遍,有点不方便。
在国际化的变量中如果有特殊字符,如@
,控制台会提示:
core-base.esm-bundler.js:1185 Message compilation error: Unexpected lexical analysis in token: 'EOF'
![在这里插入图片描述](https://img-blog.csdnimg.cn/807bb5dd270b4451a5a23ff7ff9d9ea2.png)
要把特殊字符用{''}
来包裹。
还有一个最坑,我上面代码本来是这样写的:
async function createI18nOptions() {
const defaultLocal = await import(`./lang/${locale}.ts`)
const message = defaultLocal.default?.message ?? {}
return {
messages: {
message
const options = await createI18nOptions();
export const i18n = createI18n(options)
本地是没问题,但是当我去npm run build
的时候就报错:
Top-level await is not available in the configured target...
根据网上答案解决后发现发到线上直接白屏了。应该是还没兼容top await
的这种语法?
在配置vue-i18n时,设置silentTranslationWarn: true, 去除国际化警告
const i18n = new VueI18n({
// 设置本地语言
// 值: en | zh
locale: getLanguage(),
messages,
silentTranslationWarn: true, // 去除国际化警告
1.请求错误,返回转态时候无法使用vue-i18n
Uncaught SyntaxError: Must be called at the top of a `setup` function
at createCompileError ( vue - i18n . js ? v = 465 da450 : 419 )
at createI18nError ( vue - i18n . js ? v = 465 da450 : 2397 )
at useI18n ( vue - i18n . js ? v = 465 da450 : 3696 )
at status . ts ? t = 1615278376635 : 3
Vue 3中使用i18n(国际化)可以通过多种方式实现。以下是几种常见的方法:
1. 使用Vue官方推荐的vue-i18n库:vue-i18n是一个强大的国际化插件,能够与Vue 3完美配合。可以通过npm安装并在Vue应用中引入,然后定义多语言文本资源,根据语言环境动态切换显示的文本内容。
2. 使用Composition API自定义国际化逻辑:Vue 3的Composition API使得我们能够更灵活地组织代码逻辑。你可以自己编写一个国际化逻辑的Composition函数,然后在需要的地方调用该函数获取对应的翻译文本。
3. 使用第三方库:除了vue-i18n之外,还有其他第三方库也可以实现国际化功能,比如vue-gettext、vuex-i18n等。你可以根据自己的需求选择合适的库来使用。
无论你选择哪种方式,都需要在Vue应用中配置语言环境,并提供多语言文本资源。具体如何配置和使用,请参考对应的文档和示例代码。希望这些信息对你有所帮助!如果你还有其他问题,请继续提问。