【问题标题】:Components which are not defined in SFC are not shown using Vue3 Router?未在 SFC 中定义的组件不使用 Vue3 Router 显示?
【发布时间】:2021-01-30 01:37:35
【问题描述】:

现在我正在尝试使用 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;

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>

渲染后路由器视图中没有内容。我该如何解决?

【问题讨论】:

  • 在您的App.vue 中用div 包装所有内容并添加id: 'app' 我的意思是&lt;div id="app"&gt;everything here&lt;/div&gt;
  • 尝试从import Home from '../views/Home.vue'的文件中导入主页和关于视图
  • 不幸的是,它也不起作用。
  • 确保你的 About.vue 文件是这样的:&lt;template&gt; &lt;h1&gt;About&lt;/h1&gt; &lt;/template&gt;
  • 和以前一样。

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


【解决方案1】:

我尝试了您的示例 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 }
];

【讨论】:

    猜你喜欢
    • 2022-11-02
    • 2021-03-08
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2021-09-12
    • 2020-01-23
    • 1970-01-01
    相关资源
    最近更新 更多