Home > database >  Vue.component is not a function / Migrating from Vue 2 to Vue 3 Version
Vue.component is not a function / Migrating from Vue 2 to Vue 3 Version

Time:04-13

I am trying to update the Vue version in a project from 2 to 3. The thing is, that I have to use .js files, no .vue. The problem is, that I cannot find a substitution for "Vue.component".

My app.js

    // Vue Router 4
    var router = VueRouter.createRouter({
        history: VueRouter.createWebHashHistory(),
        routes,
      });

    // Create Vuex store
    var store = Vuex.createStore({
        state: {
            // state 
        }
    });

    // Vue 3
    var app = Vue.createApp({});

    app.use(router);
    app.use(store);
    app.mount('#app');

One of the components:

component-ex.js

Vue.component('component-ex', {});

// I also tried app.component('component-ex', {});

Then I import the app and all components via index.html

Index.html

    <script src="https://unpkg.com/vue@3"></script>
    <script src="https://unpkg.com/vue-router@4"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuex.global.js"></script>

    <script src="app.js"></script>
    <script src="/components/component-ex.js"></script>


In the version 2 everything worked but now it throws an error: Vue.component is not a function

CodePudding user response:

From the Vue docs:

The .mount() method should always be called after all app configurations and asset registrations are done. Also note that its return value, unlike the asset registration methods, is the root component instance instead of the application instance.

So your index.html should probably look more like this:

    <script src="https://unpkg.com/vue@3"></script>
    <script src="https://unpkg.com/vue-router@4"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuex.global.js"></script>

    <script src="app.js"></script>
    <script src="/components/component-ex.js"></script>
    <script src="/components/another-component.js"></script>
    <script src="/components/yet-another-component.js"></script>
    
    <script>app.mount('#app');</script>
  • Related