【问题标题】:VueJS-3 How to render <router-view></router-view> from vue-router?VueJS-3 如何从 vue-router 渲染 <router-view></router-view>?
【发布时间】:2021-05-26 06:39:18
【问题描述】:

在 vuejs 2 中,我能够通过返回渲染 html 标记直接在路由器中渲染。我正在尝试使用 vue-router 4 在 vue3 中做同样的事情,但它似乎不起作用:

{
        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.js vue-router vuejs3 vue-router4


    【解决方案1】:

    来自 Vue 3 渲染函数docs

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

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

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

    或者,如果您想使用runtime compiler,您可以使用template 选项:

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

    【讨论】:

    • 从Vue Router 4开始,可以直接使用RouterView组件:path: 'my-path', component: RouterView, children: [...]。来源:github.com/vuejs/vue-router/issues/2105#issuecomment-761854147
    • @Papooch - 谢谢,这是很好的信息和更优雅的解决方案。也许您可以考虑将其作为单独的答案发布
    • 我不想从链接的评论者那里窃取信用,但我想我过多地关注虚假的互联网积分,所以我不妨将其发布为答案:)
    【解决方案2】:

    从 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

    附:根据链接的问题,据称&lt;transition&gt; 在您使用此技术时会出现一些问题,因此请谨慎使用。

    【讨论】:

      猜你喜欢
      • 2020-04-02
      • 2022-11-09
      • 2020-04-07
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2017-10-15
      相关资源
      最近更新 更多