在Vue項目中,我們一般會設置一個路由導航守衛(wèi)闷供,為防止用戶未登錄直接從地址欄輸入地址訪問網(wǎng)站其他頁面碎赢。其中路由導航守衛(wèi)使用Vue-router提供的方法來實現(xiàn)。
https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
1.在路由的js文件導入VUE路由對象并掛載
import Router from 'vue-router'
Vue.use(Router)
2.創(chuàng)建路由實例
const router = new Router({
routes: [
{ path: '/', redirect: '/login' },
{ path: '/login', component: Login },
{ path: '/home', component: Home}
]
})
3.掛載路由導航守衛(wèi)
// 掛載路由導航守衛(wèi)
router.beforeEach((to, from, next) => {
// to 將要訪問的路徑
// from 代表從哪個路徑跳轉而來
// next 是一個函數(shù)账蓉,表示放行
// next() 放行 next('/login') 強制跳轉
if (to.path === '/login') return next()
// 獲取token
const tokenStr = window.sessionStorage.getItem('token')
if (!tokenStr) return next('/login')
next()
})