vue 基於abstract 路由模式 實現頁面內嵌

abstract 路由模式

abstract 是vue路由中的第三種模式,自己是用來在不支持瀏覽器API的環境中,充當fallback,而不管是hash仍是history模式都會對瀏覽器上的url產生做用,本文要實現的功能就是在已存在的路由頁面中內嵌其餘的路由頁面,而保持在瀏覽器當中依舊顯示當前頁面的路由path,這就利用到了abstract這種與瀏覽器分離的路由模式。javascript

路由示例

export const routes = [
  { 
 
   
    path: "/",
    redirect: "abstract-route",
  },
  { 
 
   
    path: "/embed-route",
    name: "embedded",
    component: () =>
      import(/* webpackChunkName: "embed" */ "../views/embed.vue"),
  },
  { 
 
   
    path: "/abstract-route",
    name: "abstract",
    component: () =>
      import(/* webpackChunkName: "abstract" */ "../views/abstract.vue"),
  },
];

const router = new VueRouter({ 
 
   
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

本次示例有兩個路由,分別爲abstract,embedded,其中abstract視圖上展開一個抽屜,抽屜當中顯示embedded的視圖。即:vue

// abstract views
<template>
  <div>
    <RouterDrawer
      :visible.sync="visible"
      :path="{ name: 'embedded' }"
      size="50%"
      title="drawer comps"
    ></RouterDrawer>
    <el-button @click="visible = true">open drawer</el-button>
  </div>
</template>


// embedded views
<template>
  <div>
    embedded views
  </div>
</template>

在這裏插入圖片描述

router-drawer 封裝

當前項目默認是history 的路由模式,所以在進入abstract頁面時,瀏覽器Url爲http://127.0.0.1:8010/abstract-route,而router-drawer要作的是在此基礎上,從新實例化一個abstract模式的路由,而後在組件當中利用<router-view />去掛載要被內嵌的目標頁面。即:java

<template>
  <el-drawer
    :visible.sync="visible"
    v-bind="$attrs"
    :before-close="handleClose"
  >
    <router-view />
  </el-drawer>
</template>
<script>
import { 
 
    routes } from "../router/index";
import VueRouter from "vue-router";

export default { 
 
   
  name: "router-drawer",
  props: { 
 
   
    path: { 
 
   
      type: Object,
      required: true,
    },
    visible: { 
 
   
      type: Boolean,
      required: true,
      default: false,
    },
  },
   // 此處實例化一個新的router來配合當前頁面的router-view
  router: new VueRouter({ 
 
   
    mode: "abstract",
    base: "/",
    routes,
  }),
  methods: { 
 
   
    handleClose() { 
 
   
      this.$emit("update:visible", false);
    },
  },
  mounted() { 
 
   
    console.log("drawer router", this.$router);
    this.$router.push(this.path);
  },
};
</script>

經過打印日誌能夠得出兩個實例化的路由:
在這裏插入圖片描述
這樣便可實如今不改變當前頁面path的前提下加載其餘路由中的views了。webpack

代碼示例git

本文同步分享在 博客「j_bleach」(CSDN)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。github

相關文章
相關標籤/搜索