How to Use Slots in Router-View

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 Answer

Slot can work in router-view, that's for sure =>

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,
  },
];
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest