Vue3能否直接在路由中用模板创建组件?为何代码无页面显示?
问题原因及解决办法
你的代码里最直接的问题是模板字符串里的HTML标签用了HTML实体转义(<、>),Vue会把这些转义字符当成普通文本解析,不会渲染成<section>元素,所以页面看起来是空的。
修复步骤
- 把模板里的
<换成<,>换成>,直接写正常的HTML标签:
const sampleComponent = { template: `<section class='px-container py-20'>test</section>` }
- 额外检查两个容易忽略的点:
- 确保Vue实例已经挂载了路由,比如在
main.js里有app.use(router) - 确保根组件(比如
App.vue)里已经添加了<router-view>标签,路由匹配的组件会渲染到这个标签的位置
- 确保Vue实例已经挂载了路由,比如在
完整示例代码
import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import App from './App.vue' const sampleComponent = { template: `<section class='px-container py-20'>test</section>` } const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), scrollBehavior(to, from, savedPosition) { if (savedPosition) return savedPosition; else return { top: 0 }; }, routes: [ { path: "/", name: "homepage", component: sampleComponent } ] }); const app = createApp(App) app.use(router) app.mount('#app')
同时App.vue里要包含:
<template> <router-view></router-view> </template>
内容的提问来源于stack exchange,提问作者xtreebug
相关产品推荐
相关产品推荐

