【问题标题】:Render default child vue-router 4渲染默认子 vue-router 4
【发布时间】:2022-01-28 18:23:03
【问题描述】:

我想问一下渲染默认子视图的问题。 我知道 topic 存在类似的问题,但我很确定它适用于 VUE2 和较旧的 vue-router。我在呈现视图类别的默认子项时遇到问题。当我去<router-link :to="{ name: routeName, params: { category: item.id } } 除了<router-view /> 它是空的,一切都可以渲染...

我想出了一个使用 beforeUpdate(),beforeCreate() 的解决方案,但这似乎是在重新发明轮子。 如果我转到 /category/{id} 然后转到 /category/{id}/room/{id} 并返回一页,将呈现默认视图

进入/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 - 查看

<template>
  <div class="control">
    <div class="left">
      [...]
    </div>
    <div class="right">
      <router-view />
    </div>
  </div>
</template>

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

【问题讨论】:

    标签: javascript vue.js vue-router vuejs3


    【解决方案1】:

    如果你的默认组件是Category,你必须像这样创建路由:

    {
      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,
        },
      ],
    },
    

    默认情况下,它会渲染 Category 组件,如果您在 url 中添加 id,它将转到 Devices 组件

    【讨论】:

    • 谢谢,但不是重点。我会扩展一点:我在左侧面板中有视图 Category 在右侧面板中有 router-view 我很想有这样的场景: - 我去 /category/categoryId - 它在左侧生成一个视图(固定)菜单,在router-view 的右侧它会生成一个名为 FavouriteDevicesInCategory 的默认视图 - 我从左侧菜单中选择一个房间 - 转到 /category/categoryId/room/roomId - 在左侧生成一个视图(固定)菜单,右侧是一个名为“设备”的组件,我不想访问 /category - 没有 id
    【解决方案2】:

    我想我找到了一个解决方案,有点乱,但它似乎是解决这个问题的最佳解决方案

    {
      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,
        },
      ],
    },
    

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2021-07-28
      • 2020-03-24
      • 1970-01-01
      • 2017-05-25
      • 2018-02-11
      • 2017-07-14
      • 2021-05-26
      • 1970-01-01
      相关资源
      最近更新 更多