Components which are not defined in SFC are not shown using Vue3 Router?

1.7k Views Asked by At

Now I am trying to create a front-end of a website using Vue3. But now I am having an issue using the Router. Here's my code.

Main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App).use(router).mount('#app')

router/index.js

import {createRouter, createWebHistory} from 'vue-router'

const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }

const routes = [
    { path: '/', component: Home },
    { path: '/about', component: About },
  ]

const router = createRouter({
    history: createWebHistory(),
    routes
});

export default router;

App.vue

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <h1>Hello App!</h1>
  <p>
    <!-- use the router-link component for navigation. -->
    <!-- specify the link by passing the `to` prop. -->
    <!-- `<router-link>` will render an `<a>` tag with the correct `href` attribute -->
    <router-link to="/">Go to Home</router-link>
    <router-link to="/about">Go to About</router-link>
  </p>
  <!-- route outlet -->
  <!-- component matched by the route will render here -->
  <router-view></router-view>
</template>

<script>
export default {
  name: 'App',
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

There's no content in router-view after rendering. How can I fix it?

1

There are 1 best solutions below

0
On BEST ANSWER

I tried out your example here and i got the same behavior as you have but after defining components inside single files they work fine:

import Contact from "./Contact.vue";
import About from "./About.vue";

const Home = { name: "Home", template: "<div>Home</div>" };// this will not be displayed

const routes = [
  { path: "/", name: "Home", component: Home },
  { path: "/contact", name: "Contact", component: Contact },
  { path: "/about", component: About }
];