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