You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3能否直接在路由中用模板创建组件?为何代码无页面显示?

问题原因及解决办法

你的代码里最直接的问题是模板字符串里的HTML标签用了HTML实体转义(&lt;、&gt;),Vue会把这些转义字符当成普通文本解析,不会渲染成<section>元素,所以页面看起来是空的。

修复步骤

  1. 把模板里的&lt;换成<,&gt;换成>,直接写正常的HTML标签:
const sampleComponent = {
  template: `<section class='px-container py-20'>test</section>`
}
  1. 额外检查两个容易忽略的点:
    • 确保Vue实例已经挂载了路由,比如在main.js里有app.use(router)
    • 确保根组件(比如App.vue)里已经添加了<router-view>标签,路由匹配的组件会渲染到这个标签的位置

完整示例代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 03:05:30