How to use slots in router-view

前提是你 提交于 2019-12-11 15:09:02

问题


I'm trying to use slot in router-view and unable to get the slot data in child component.

I search a lot, this example seems to work in single js file. But, when I use slot in separate file component, it doesn't work for me.

I'm using vue": "^2.1.2" and "vue-router": "^3.0.2" I have tried this code:

AppContainer.vue

<router-view>
  <p> This is a default slot</p>
  <p slot="test"> This is a named slot</p>
</router-view>

ComponentA.vue

<template>
  <div>
    ...
    <slot/>
  </div>
</template>

ComponentB.vue

<template>
  <div>
    <slot name="test"><slot/>
    ...
  </div>
</template>

route.js

{
  path: '/performance',
  redirect: '/performance/evaluator',
  component: {
     render(c) {
       return c('router-view')
     }
  },
  children: [
     {
       path: 'evaluator',
       name: 'ComponentA',
       component: ComponentA
      },
      {
        path: 'management',
        name: 'ComponentB',
        component: ComponentB
      }
   ]
}

I'm getting no slot data in both components.


回答1:


Slot can work in router-view, that's for sure => https://codesandbox.io/s/vue-routing-example-14843

I believe what went wrong is the way you config the routes, especially

 component: {
     render(c) {
       return c('router-view')
     }
  },

if you want the parent component to render nothing, it would be simpler to separate the path config


[
  // ...
  {
    path: '/performance',
    redirect: '/performance/evaluator',
  },
  {
    path: '/performance/evaluator',
    name: 'ComponentA',
    component: ComponentA,
  },
  {
    path: '/performance/management',
    name: 'ComponentB',
    component: ComponentB,
  },
];


来源:https://stackoverflow.com/questions/58606395/how-to-use-slots-in-router-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!