在 Vue 中实现动态路由可以使用递归的方式,具体步骤如下:

  1. 在路由配置文件中定义一个动态路由,例如:
{
  path: '/:id',
  name: 'dynamic',
  component: Dynamic,
  props: true
}
  1. 在组件中通过 $route.params.id 获取当前路由的参数值,然后根据该值进行判断和处理,例如:
<template>
  <div>
    <h2>动态路由</h2>
    <div v-if="id === '1'">
      <p>这是第一个动态路由页面</p>
    </div>
    <div v-else-if="id === '2'">
      <p>这是第二个动态路由页面</p>
    </div>
    <div v-else>
      <p>未知的动态路由页面</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Dynamic',
  props: ['id']
}
</script>
  1. 如果需要在动态路由中嵌套子路由,则可以使用递归的方式。在父组件中使用 <router-view> 来渲染子路由,然后在子组件中再次使用 <router-view> 来渲染嵌套的子路由,例如:
{
  path: '/:id',
  name: 'dynamic',
  component: Dynamic,
  props: true,
  children: [
    {
      path: 'child',
      name: 'child',
      component: Child,
      props: true,
      children: [
        {
          path: 'grandchild',
          name: 'grandchild',
          component: Grandchild,
          props: true
        }
      ]
    }
  ]
}
  1. 在父组件 Dynamic 中使用 <router-view> 来渲染子路由 Child,然后在子组件 Child 中再次使用 <router-view> 来渲染嵌套的子路由 Grandchild,例如:
<template>
  <div>
    <h2>动态路由</h2>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'Dynamic',
  props: ['id']
}
</script>
<template>
  <div>
    <h3>子路由</h3>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'Child',
  props: ['id']
}
</script>
<template>
  <div>
    <h4>嵌套子路由</h4>
    <p>当前路由参数为:{{ id }}</p>
  </div>
</template>

<script>
export default {
  name: 'Grandchild',
  props: ['id']
}
</script>
Vue 递归实现动态路由 - 详细指南

原文地址: https://www.cveoy.top/t/topic/mAS2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录