vue 解決addRoutes動態添加路由後,刷新失效問題

你是電,你是光,你是最美的太陽🌞

前言

某些場景下咱們須要利用addRoutes動態添加路由,可是刷新後就會失效,前段時間項目裏恰好遇到了這個應用場景,因此就花時間研究了一下,作下分享跟記錄,說的不對的地方,請你們指正。
應用場景:用戶a登陸進系統,頁面上有個按鈕, 點擊以後會動態添加路由而且跳轉,跳轉過去以後,用戶刷新後也會停留在當前頁面。 不點這個按鈕,瀏覽器輸入地址,用戶會跳到404頁面

github:https://github.com/Mrblackant...
在線查看:http://an888.net/router/keepR...
圖片描述vue

思路

1.用戶點擊按鈕,用addRutes動態添加路由並跳轉,並把路由保存;
2.用戶在新跳轉的頁面,刷新時利用beforeEach進行攔截判斷,若是發現以前有保存路由,而且判斷新頁面只是刷新事件,再將以前保存的路由添加進來;

代碼

1.按鈕點擊,保存路由並跳轉git

(1).在router/index.js裏聲明一個數組,裏邊是一些固定的路由,好比你的登陸頁面、404等等
//router/index.js
export const constantRouterMap=[
    {
      path: '/',
      // name: 'HelloWorld',
      component: HelloWorld
    }
  ]
Vue.use(Router)
export default new Router({
  routes: constantRouterMap
})
(2).按鈕點擊,跳轉、保存路由;
注意,保存路由這一步驟,要作進要跳轉到的組件裏,這是爲了防止在beforeEach攔截這邊產生死循環
添加路由須要兩點,一是path,二是component,你能夠封裝成方法,看着就會簡潔一點,我這裏就不作了
記得要用concat方法鏈接,固定的路由和動態新加的路由,這樣瀏覽器回退的時候也能正常返回
//點擊跳轉
<template>
  <div>
    點擊新增 動態路由: "secondRouter"
    <br/>
    <el-button @click="srouter" type="primary">新增動態路由</el-button>

  </div>
</template>

<script>
import router from 'vue-router'
import {constantRouterMap} from '@/router'


export default {
  name: 'kk',
  mounted(){
  },
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods:{
    srouter(){
      let newRoutes=constantRouterMap.concat([{path:'/secondRouter',
        component :resolve => require(["@/components/kk"], resolve )
      }])
      this.$router.addRoutes(newRoutes)
      this.$router.push({path:'/secondRouter'})
    }
  }
}
</script>

//跳轉過去的component組件,xxx.vue
<template>
  <div class="secondRoute">
    恭喜你,動態添加路由成功,瀏覽器的連接已經變化;

    <h3>不管你怎麼刷新我都會留在當前頁面</h3>
    <h3>而且點擊瀏覽器回退鍵,我會跳到以前頁面,不會循環</h3>

  </div>
</template>

<script>
import router2 from '@/router'
import router from 'vue-router'
export default {
  name: 'HelloWorld',
  mounted(){
      localStorage.setItem('new',JSON.stringify({'path':'/secondRouter','component':'kk'}))//保存路由
  },
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods:{
  }
}
</script>

2.路由攔截beforeEachgithub

這裏攔截的時候,就判斷localStorage裏邊有沒有保存新的動態路由,若是有,就進行判斷,邏輯處理,處理完以後就把保存的路由清除掉,防止進入死循環。
進入第一層判斷後,須要再次判斷一下是否是頁面的刷新事件
import router from './router'
import { constantRouterMap } from '@/router' //router裏的固定路由
router.beforeEach((to, from, next) => {
  if (localStorage.getItem('new')) {
    var c = JSON.parse(localStorage.getItem('new')),
    lastUrl=getLastUrl(window.location.href,'/');

    if (c.path==lastUrl) { //動態路由頁面的刷新事件
      let newRoutes = constantRouterMap.concat([{
        path: c.path,
        component: resolve => require(["@/components/" + c.component + ""], resolve)
      }])
      localStorage.removeItem('new')
      router.addRoutes(newRoutes)
      router.replace(c.path) //replace,保證瀏覽器回退的時候能直接返回到上個頁面,不會疊加

    } 
  } 
  next()

})

var getLastUrl=(str,yourStr)=>str.slice(str.lastIndexOf(yourStr))//取到瀏覽器出現網址的最後"/"出現的後邊的字符

ps:一開始我還覺得匹配不到路由跳轉404要在攔截這裏處理,後來發現根本不用,直接在註冊路由的時候加上下邊兩段就好了:vue-router

export const constantRouterMap = [{
    path: '/',
    component: HelloWorld
  }, 
  {//404
    path: '/404',
    component: ErrPage
  },
  { //重定向到404
      path: '*', redirect: '/404' }
]

總體的思路大概就是這樣,主要就是利用了beforeEach攔截+localStorage的數據存儲,就能完成,addRoutes動態添加路由刷新不失效功能。
不足的地方還請你們多多指正數組

相關文章
相關標籤/搜索