我认为这个问题源于在Vue.js 3
与Vue Router 4
中有多个孩子的父模板。
App.vue
文件:
<template>
<div id="app">
<main id="content">
<div id="nav">
<!--<router-link to="/about">About</router-link>-->
<router-link to="/information">Information</router-link>
<router-link :to="{ path: '/create', name: 'PostCreate'}">Create</router-link>
</div>
<router-view></router-view>
</main>
</template>
router-link to="/information"
链接工作正常。它只是加载视图,里面没有其他组件。
另一个router-link :to="{ path: '/create', name: 'PostCreate'}"
在反复尝试加载组件约50次后失败,并在控制台中记录此情况:
[Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next
at <PostCreate>
at <PostCreate>
at <PostCreate>
... // repeats over and over again until
at <PostCreate onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< null > >
at <RouterView>
at <App>
at <App>
vuerouter.js
const routes = [
{
path: '/',
name: 'HomeView',
component: HomeView
},
{
path: '/information',
name: 'Information',
component: () => import(/* webpackChunkName: "Information" */ '../views/information/Information.vue')
}
,
{
path: '/create',
name: 'PostCreate',
component: () => import(/* webpackChunkName: "Create" */ '../views/posts/PostCreate.vue')
}
];
Information.vue
和PostCreate.vue
之间的唯一区别是后者导入另一个vue
组件来生成form
,以便用户创建帖子。
Information.vue
<template>
<div>
<p>I am full of good info</p>
</div>
</template>
<script>
export default {
name: 'Information'
}
</script>
PostCreate.vue
<template>
<div class="content">
<h1>I make a form</h1>
<Post-Create></Post-Create>
</div>
</template>
<script>
import PostCreate from "../../components/PostCreate.vue";
export default {
name: "PostCreate",
components: {
"Post-Create": PostCreate
}
}
</script>
为什么在Vue.js 3和Vue-Router 4中出现这个问题,而它以前工作得很好?怎么解呢?
这是因为PostCreate
视图试图递归加载自己。由于您为视图和子组件使用了相同的名称,因此父名称会覆盖注册中的子名称,并且视图会尝试加载自己而不是子组件。
这是等价的,这也会导致视图试图加载自己。
<template>
<div class="content">
<h1>I make a form</h1>
<PostCreate></PostCreate>
</div>
</template>
<script>
export default {
name: "PostCreate",
};
</script>
你不会得到Failed to resolve component
错误,因为它需要<PostCreate></PostCreate>
本身。你会得到相同的递归错误。
所以你只需要重命名子组件。对于不同的组件,特别是在较大的项目中,总是使用不同的文件名也是一个很好的做法,以保持文件的清晰。