Home > Software engineering >  How to properly register a component in a Vue 3 Composition API app?
How to properly register a component in a Vue 3 Composition API app?

Time:09-01

I'm trying to build an app with two layout, one with header and everything, one with just the background for some special pages(like login pages).

I've tried the following:

Created 2 view page:

layouts/Default.vue

<template>
   <header >
      <Header ></Header>
   </header>

   <div >
      <div >
         <slot />
      </div>
   </div>
</template>

<script setup lang="ts">
import Header from "../components/Header.vue";
</script>

and

layouts/Plain.vue

<template>
   <div >
      <div >
         <slot />
      </div>
   </div>
</template>

In my router/index.ts, I provide a "meta"

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { layout: 'plain' },
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
  ],
});

In my App.vue: I try to use this to create a component that wraps my routerView:

<script setup lang="ts">
import { computed } from "vue";
import { RouterView, useRoute } from "vue-router";

const route = useRoute();

const layout = computed(() => {
  return (route.meta.layout || 'default');
});
</script>

<template>
  <div id="root"
       >
    <component :is="layout">
      <RouterView></RouterView>
    </component>

  </div>
</template>

And more important, in my main.ts file, I did try to register them:

import { createPinia } from 'pinia';
import Vue, { createApp } from 'vue';

import App from './App.vue';
import router from './router';

import './assets/main.css';
import Plain from './layouts/Plain.vue';
import Default from './layouts/Default.vue';


const app = createApp(App);

app.component('default', Default);
app.component('plain', Plain)

app.use(createPinia());
app.use(router);

app.mount('#app');

But when I try to display ANY page, I get this:

Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/vue.js?v=7cc2bcdd' does not provide an export named 'default' (at main.ts:2:8)

So I guess, that app.component('vue-name', component) is not the correct approach, but I can't find how?

CodePudding user response:

The error is unrelated to your component registration, but rather it points to this:

                  
  • Related