VueJS-3 如何<router-view></router-view>从 vue-router 渲染?



在vuejs 2中,我可以通过返回渲染html标签直接在路由器中渲染。我试图用vue-router 4在vue- 3中做同样的事情,但它似乎不起作用:

{
path: 'posts',
redirect: '/posts/all',
name: 'posts',
meta: {'breadcrumb': 'Posts'},
component: {
render() {
return h('router-view');
}
},
children: [ //Lots of sub routes here that I could load off the anonymous router-view]
}

知道如何让组件渲染路由视图,并允许我使用我的子路由吗?我宁愿不加载一个单一的组件,只是为了容纳";这在vue-router 3中工作得很好,不知道4有什么问题。我还从'vue'导入{h}。

从Vue 3渲染函数文档:

3。由于VNodes与上下文无关,我们不能再使用字符串ID来隐式查找已注册的组件。相反,我们需要使用导入的resolveComponent方法:

您仍然可以使用h('div'),因为它不是组件,但对于组件,您必须使用resolveComponent:

import { h, resolveComponent } from Vue;  // import `resolveComponent` too
component: {
render() {
return h(resolveComponent('router-view'))
}
},

或者,如果您想使用运行时编译器,您可以使用template选项(不推荐,因为编译器会增加应用程序大小):

component: {
template: `<router-view></router-view>`
}

从Vue Router 4开始,你可以直接使用RouterView组件:

import { RouterView } from 'vue-router';
//...
{
path: 'posts',
redirect: '/posts/all',
name: 'posts',
meta: {'breadcrumb': 'Posts'},
component: RouterView, // <- here
children: [ /* ... */ ]
}

来源:https://github.com/vuejs/vue-router/issues/2105 issuecomment - 761854147

注:根据链接的问题,当您使用此技术时,<transition>据称存在一些问题,因此请谨慎使用。

最新更新