如何修复Vue I18n Uncaught TypeError:Cannot read property ‘config’ of undefined

2021年11月29日20:05:40 发表评论 3,079 次浏览

了解如何轻松修复 Vue.js 项目中 Vue i18n 模块的初始化错误。

如何修复Vue I18n Uncaught TypeError:Cannot read property 'config' of undefined

如何修复错误Cannot read property 'config' of undefined?我一直在开发一个需要以多种语言进行本地化的 Vue.js 应用程序。对于 Vue.js,实现 i18n的最佳模块是 Vue.js I18N。安装后,我尝试按照文档中的描述对其进行初始化,但是,我在代码中遗漏了一些内容并最终出现此异常:Uncaught TypeError: Cannot read property 'config' of undefined。

以下代码将在任何 Vue 应用程序中触发上述异常:

// main.js
// Example of regular VueJS app with translation
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

// 1. Import i18n
import VueI18n from 'vue-i18n';

// 2. Create VueI18n instance with options
const i18n = new VueI18n({
    // set locale
    locale: 'en',
    // set locale messages
    messages: {
        en: {
            message: {
                hello: 'hello world'
            }
        },
        ja: {
            message: {
                hello: 'こんにちは、世界'
            }
        }
    }
});

Vue.config.productionTip = false;

new Vue({
    router,
    store,
    i18n,
    render: h => h(App)
}).$mount("#app");

修复错误Cannot read property 'config' of undefined:如果你面临同样的异常,你可能正在对代码做同样的事情。你导入 i18n 模块,创建一个新实例并将其注入 Vue 实例。但是,你忘记指示 Vue.js 使用新模块。要修复此错误,只需在创建实例之前指示 Vue 应使用 Vue I18N 模块,如下所示:

// 1. Import the library
import VueI18n from 'vue-i18n'

// 2. Important! Just right before initializing the I18n instance, use the module
Vue.use(VueI18n)

// 3. Create I18n instance
const i18n = new VueI18n({
    // ...
});

// 4. Load into vue
new Vue({
    i18n,
    render: h => h(App)
}).$mount("#app");

没有这个乏味异常的最终代码将如下所示:

// main.js
// Example of regular VueJS app with translation
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

// 1. Import i18n
import VueI18n from 'vue-i18n';

// 2. Just right before initializating the I18n instance, use the module
Vue.use(VueI18n)

// 3. Create VueI18n instance with options
const i18n = new VueI18n({
    // set locale
    locale: 'en',
    // set locale messages
    messages: {
        en: {
            message: {
                hello: 'hello world'
            }
        },
        ja: {
            message: {
                hello: 'こんにちは、世界'
            }
        }
    }
});

Vue.config.productionTip = false;

new Vue({
    router,
    store,
    i18n,
    render: h => h(App)
}).$mount("#app");

快乐编码❤️!

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: