vue.js - SFC 中未定义的组件不会使用 Vue3 Router 显示?

标签 vue.js vue-component vue-router vuejs3 vue-router4

现在我正在尝试使用Vue3创建一个网站的前端。但现在我在使用路由器时遇到了问题。 这是我的代码。

Main.js

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

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

路由器/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;

应用程序.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>

渲染后router-view中没有内容。我该如何修复它?

最佳答案

我尝试了你的例子here我得到了与您相同的行为,但是在单个文件中定义组件后,它们工作正常:

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 }
];

关于vue.js - SFC 中未定义的组件不会使用 Vue3 Router 显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64373774/

相关文章:

javascript - Vue.js - 删除带有组件或类似组件的冗长引导输入字段代码

javascript - 停止多次点击 vue.js

javascript - 为什么 keydown 在手机上不起作用? vue.js 2

javascript - 在Vue 2路由器中设置嵌套可选参数

javascript - 动态 Nuxt 页面选择

vue.js - Vuejs 有多个组件共享变量和函数

vue.js - Vuetify.js - <v-menu> 内的 <v-text-field> 没有 <v-menu> 消失就无法聚焦

vue.js - Vue-router:beforeEnter guard 对于子路径不能正常工作

vue.js - vue中如何将props从父类传递给孙子类

vue.js - VueJS 精确事件类