Vue.js 3-在VUE中使用Vue i18n插件时出错-无法设置未定义的属性';_vm
我刚刚开始使用Vue.js,并通过一些在线代码片段和教程学习它。我正在尝试为我的VUE项目实现国际化支持,但在Web控制台中遇到错误。
以下是我的代码片段
main.js
import { createApp } from 'vue';
import App from './App.vue';
import VueI18n from 'vue-i18n'
import router from './router/index'
function loadLocaleMessages () {
const locales = require.context('./locales', true, /[A-Za-z0-9-_,s]+.json$/i)
const messages = {}
locales.keys().forEach(key => {
const matched = key.match(/([A-Za-z0-9-_]+)./i)
if (matched && matched.length > 1) {
const locale = matched[1]
messages[locale] = locales(key)
}
})
return messages
}
const i18n = VueI18n({
locale: process.env.VUE_APP_I18N_LOCALE || 'en',
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
messages: loadLocaleMessages()
})
const app = createApp(App);
app.use(router);
app.use(i18n);
app.mount('#app');
这是我的HelliI18n.vue文件,我要在其中使用翻译
<template>
hello
<p>{{ $t('hello') }}</p>
</template>
<script>
export default {
name: 'HelloI18n'
}
</script>
以下代码摘自Package.json文件(适用于版本)
"dependencies": {
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-i18n": "^8.22.1",
"vue-router": "^4.0.0-0"
},
"devDependencies": {
"@intlify/vue-i18n-loader": "^1.0.0",
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0-0",
"vue-cli-plugin-i18n": "~1.0.1"
},
当我运行项目时,在Web控制台上看到以下错误
Uncaught TypeError: Cannot set property '_vm' of undefined
at VueI18n (vue-i18n.esm.js?a925:1173)
at eval (main.js?56d7:19)
at Module../src/main.js (app.js:1167)
at __webpack_require__ (app.js:854)
at fn (app.js:151)
at Object.1 (app.js:1228)
at __webpack_require__ (app.js:854)
at checkDeferredModules (app.js:46)
at app.js:994
at app.js:997
我有什么地方做错了吗?有什么我遗漏的依赖吗?如有任何帮助,我们将不胜感激。
解决方案
您应该安装与Vue 3兼容的vue-i18n@next
:
npm install --save vue-i18n@next
或通过使用纱线
yarn add vue-i18n@next
基本用途:
import { createApp } from "vue";
import App from "./App.vue";
import { createI18n } from "vue-i18n";
const i18n = createI18n({
legacy: false,
locale: "ja",
globalInjection: true,
messages: {
en: {
message: {
language: "English",
greeting: "Hello !"
}
},
ar: {
message: {
language: "العربية",
greeting: "السلام عليكم"
}
},
es: {
message: {
language: "Español",
greeting: "Hola !"
}
}
}
});
createApp(App).use(i18n).mount("#app");
App.vue
<template>
<div>
<select v-model="lang">
<option value="en">English</option>
<option value="ar">العربية</option>
<option value="es">Español</option>
</select>
<h2>{{ $t("message.greeting", {}, { locale: lang }) }}</h2>
</div>
</template>
<script>
export default {
data() {
return {
lang: "en",
};
},
};
</script>
EXAMPLE
组合接口(setup
):
import { useI18n } from 'vue-i18n';
...
export default defineComponent({
setup() {
const { t } = useI18n();
// then use it like t('message.greeting')
}
})
相关文章