在大多數網站中,實現登陸註冊都是結合本地存儲cookie、localStorage和請求時驗證token等技術。而對於某些功能頁面,會嘗試獲取本地存儲中的token進行判斷,存在則可進入,不然跳到登陸頁或彈出登陸框。vue
而在vue單頁中,咱們能夠經過監控route對象,從中匹配信息去決定是否驗證token,而後定義後續行爲。vue-router
具體實現代碼以下:cookie
1. 利用router.beforeEach鉤子, 判斷目標路由是否攜帶了相關meta
信息網站
// router.js import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', component: require('./views/Home'), meta: { requiresAuth: true } }, ] const router = new VueRouter({ routes: routes }) router.beforeEach((to, from, next) => { let token = window.localStorage.getItem('token') if (to.matched.some(record => record.meta.requiresAuth) && (!token || token === null)) { next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() } }) export default router
2. watch route對象。原理同上。ui
<script> // App.vue export default { watch:{ '$route':function(to,from){ let token = window.localStorage.getItem('token'); if (to.matched.some(record => record.meta.requiresAuth) && (!token || token === null)) { next({ path: '/login', query: { redirect: to.fullPath } }) } else { next() } } } } </script>