Vue項目中設置全局路由導航守衛


在Vue項目中國,我們一般會設置一個路由導航守衛,為防止用戶未登錄直接從地址欄輸入地址訪問網站其他頁面。其中路由導航守衛使用Vue-router提供的方法來實現。

https://router.vuejs.org/zh/guide/advanced/navigation-guards.html

1.在路由的js文件導入VUE路由對象並掛載

 

import Router from 'vue-router'
Vue.use(Router)

 

2.創建路由實例

 

const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    { path: '/home', component: Home}
  ]
})

 

3.掛載路由導航守衛

// 掛載路由導航守衛
router.beforeEach((to, from, next) => {
  // to 將要訪問的路徑
  // from 代表從哪個路徑跳轉而來
  // next 是一個函數,表示放行
  //     next()  放行    next('/login')  強制跳轉

  if (to.path === '/login') return next()
  // 獲取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM