javascriptvue.jsvue-componentvue-clivuejs3

Vue 3 - "Failed to resolve component" with global components


My Vue components work fine when declared in the top level HTML file, like this

<body>
  <div class='app' id='app'>        
    <header-bar id='headerBar'></header-bar>        
    <journal-page></journal-page>
  </div>
  <script src="js/app.js"></script>
</body>

but using a <journal-card> component inside the <journal-page> component gives me the error:

[Vue warn]: Failed to resolve component: journal-card at <JournalPage>.

How do I fix this please?

Here's my top level code that loads the Vue components, app.js:

import * as _vue from 'vue';
import _headerBar from './widgets/headerBar.vue';
import _journalCard from './widgets/journalCard.vue';
import _journalPage from './widgets/journalPage.vue';
import _store from './data/store.js';

const app = _vue.createApp
({
    components: 
    {
        'headerBar': _headerBar,
        'journalCard': _journalCard,
        'journalPage': _journalPage     
    },
    data : _store,
    methods: {}
});
const mountedApp = app.mount('#app');

and here's my journal-page.vue container

<template>  
  <ul>
    <journal-card v-for="item in journal" :key="item.id" :entry=item></journal-card>
  </ul>
</template>

<script lang="js">
import _store from '../data/store.js';
export default {
  'data': _store
};
</script>

and journal-card.vue component

<template>
  <div>
    hi imma journal entry
  </div>
</template>

<script lang="js">
export default {
  'data': null,
  'props': [ 'entry' ]
};
</script>

Solution

  • Registering components in the root component's components option doesn't make them global. Doing that just makes them available to the root component itself, not its children.

    To register components globally, use app.component in your top-level code:

    main.js

    import { createApp } from 'vue';
    import App from './App.vue';
    import MyGlobalComponent from './components/MyGlobalComponent.vue';
    
    const app = createApp(App);
    app.component('MyGlobalComponent', MyGlobalComponent); ✅
    const mountedApp = app.mount('#app');