在 Vue 3 中,我创建了以下 Home
组件,另外 2 个组件( Foo
和 Bar
),并将其传递给 vue-router
如下图所示。 Home
组件是使用 Vue 的 component
函数创建的,而 Foo
和 Bar
组件是使用普通对象创建的。
我得到的错误:
Component is missing template or render function.
在这里, Home
组件导致了问题。我们不能将 --- 的结果传递给 vue-router
component()
的路由对象吗?
<div id="app">
<ul>
<li><router-link to="/">Home</router-link></li>
<li><router-link to="/foo">Foo</router-link></li>
<li><router-link to="/bar">Bar</router-link></li>
</ul>
<home></home>
<router-view></router-view>
</div>
<script>
const { createRouter, createWebHistory, createWebHashHistory } = VueRouter
const { createApp } = Vue
const app = createApp({})
var Home = app.component('home', {
template: '<div>home</div>',
})
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar },
],
})
app.use(router)
app.mount('#app')
</script>
请参阅 代码沙箱 中的问题。
原文由 Circuit Breaker 发布,翻译遵循 CC BY-SA 4.0 许可协议
当
app.component(...)
提供定义对象(第二个参数)时,它返回应用程序实例(以允许链接调用)。要获取组件定义,请省略定义对象并仅提供名称:演示