Home > Back-end >  Render default child vue-router 4
Render default child vue-router 4

Time:01-29

I'd like to ask about render default child for view. I know that exists topic with a similar problem but I'm pretty sure that it was for VUE2 and older vue-router. I'm having trouble rendering the default child for view Category. When I'd go to <router-link :to="{ name: routeName, params: { category: item.id } } everything render okay except <router-view /> it's empty...

I came up with a solution with beforeUpdate(),beforeCreate() but it seems like reinventing the wheel. If I go to /category/{id} then to /category/{id}/room/{id} and go back one page, the default view will be rendered

How to make the default child load after going to /category/{id}?

router.js

{
  path: '/category/:category',
  name: 'Category',
  props: true,
  component: Category,
  children: [
    {
      path: '',
      name: 'FavouriteDevicesInCategory',
      component: Devices,
      props: true,
    },
    {
      path: 'room/:room',
      name: 'Devices',
      component: Devices,
      props: true,
    },
  ],
},

Category.vue - view

<template>
  <div >
    <div >
      [...]
    </div>
    <div >
      <router-view />
    </div>
  </div>
</template>

<script>
export default {
  props: ['category', 'room'],
  /** generate default router-view */
  beforeUpdate() {
    this.$router.push('');
  },
  beforeCreate() {
    this.$router.push('');
  },
};

CodePudding user response:

If your default component is Category, you have to create the routes like this:

{
  path: '/category',
  name: 'Category',
  props: true,
  component: Category,
  children: [
    {
      path: '/:categoryId',
      name: 'FavouriteDevicesInCategory',
      component: Devices,
      props: true,
    },
    {
      path: 'room/:roomId',
      name: 'Devices',
      component: Devices,
      props: true,
    },
  ],
},

By default it will render the Category component and if you add an id to the url it will go the the Devices component

CodePudding user response:

I think I found a solution, a little messy, but it seems to be the best solution to this problem

{
  path: '/category/:category',
  // name: 'Category',
  props: true,
  component: Category,
  children: [
    {
      path: '',
      name: 'Category',
      component: Devices,
      props: true,
    },
    {
      path: 'room/:room',
      name: 'Devices',
      component: Devices,
      props: true,
    },
  ],
},
  •  Tags:  
  • Related