vue-router 多级嵌套路由 子级路由渲染


场景:路由A 引入 子路由B ,访问 子路由B 无响应:

第一步:检查确保 B 已正确引入

方案1:

A 中添加<router-view /> 用于B的呈现

--------------------------------------------

添加 router-view 简易方式 (访问B时不想出现A页面内容)

component_A.vue :

<template>
  <router-view v-if="$route.path != '/A'" />
  <div v-else>A内容</div>
</template>
--------------------------------------------
 
方案2(避免父页面需繁琐添加 <router-view v-if=... />):
路由插件: 新建文件 src\utils\routeReplaceSelf.js 
export default function routeReplaceSelf(component) {
  return {
    name: 'routerReplaceSelf',
    computed: {
      showChild() {
        const deepestMatchedRoute = this.$route.matched[this.$route.matched.length - 1];
        return deepestMatchedRoute.instances.default !== this;
      },
      cache() {
        return this.$route.meta.cache
      },
    },
    render(h) {
      const child = this.showChild ? h('router-view') : h(component);
      if (this.cache) {
        return h('keep-alive', [child])
      } else {
        return child
      }
    },
  };
}

 

src\router\index.js 路由配置中调整组件引入方式

原方式 component: () => {}  修改为 component: RouteReplaceSelf(() => {})
 
   
  import RouteReplaceSelf from "@/utils/routeReplaceSelf";
...

{
  path: "/caseManager",
  name: "caseManager",
  meta: { title: "案件列表A", cache: true },
  component: RouteReplaceSelf(() => import("@/views/authorityAdmin/caseManager")),
  children: [
    {
      path: "/caseInfo",
      name: "caseInfo",
      meta: { title: "案件详情B" },
      component: () => import("@/views/authorityAdmin/caseInfo"),
    },
  ]
}

...
效果呈现:
案件列表A -> 案件详情B 刷新B; 
案件详情B ->(返回) 案件列表A 不刷新A
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM