基於vue-admin-template開發的項目,在加了基於角色的權限控制後,刷新頁面就跳404

本文參考自https://blog.jam00.com/article/info/54.html

  最近,基於vue admin template做了個demo,在它基礎上對某些菜單加了頁面權限控制,但是現在刷新做了權限控制的頁面後,就404了,沒加權限控制的是正常的。經過一番查找,發現是因爲 vuex 中 sotre 存儲的內容會在刷新頁面時丟失導致的。

  

雖然將 next({ ...to, replace: true }) 改爲 next({ path: '/' }) 也能解決問題,但是體驗不好,一刷新就跳轉到首頁,關於next 參考

刷新頁面時打印 to.path和from.path 都是 /,無法獲取上一次路由

不過發現使用 window.location.href 可以獲取,這就好辦了

使用方法GetUrlRelativePath獲取路由( /utils/common.js)

1
2
3
4
5
6
7
8
9
10
11
export function GetUrlRelativePath(url) {
  var arrUrl = url.split('//')
 
  var start = arrUrl[1].indexOf('/')
  var relUrl = arrUrl[1].substring(start)
 
  if (relUrl.indexOf('?') !== -1) {
    relUrl = relUrl.split('?')[0]
  }
  return relUrl
}

獲取刷新前的訪問路由

1
const fromPath = GetUrlRelativePath(window.location.href)

獲取用戶的權限,動態加載路由

然後跳轉到刷新前的路由

1
next({ path: fromPath })

改動後如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is home will not trigger   afterEach hook, so manually handle it
    } else {
      const fromPath = GetUrlRelativePath(window.location.href)
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(res => { // 拉取用戶信息
          const roles = res.data.roles
          store.dispatch('GenerateRoutes', { roles }).then(() => { // 生成可訪問的路由表
            router.addRoutes(store.getters.addRouters) // 動態添加可訪問路由表
            next({ path: fromPath })
          })
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || 'Verification failed, please login again')
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否則全部重定向到登錄頁
      NProgress.done()
    }
  }
})


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章