vue之全局守卫
Vue 的路由守卫是什么东西呢?
第一次接触很懵逼,知道自己遇到了这样一个需求,
在页面之间进行路由跳转时,需要进行一个判断,如果下一个页面是需要登录后才能进入的页面,那么就需要在点击进入该页面的时候进行守卫的判断,判断用户是否登录,如果登录过了。就直接进入需要进入的页面,如果没有登录过,则进入登录页面。
那么问题来了,怎么知道登录过还是没有登录过呢?
在点击登录的时候,会请求后台的 api,这时,后台会返回一个 token 字段。我们需要将该字段存储到 storage 或者 cookie 中。然后在路由守卫中加入读取出来判断他是否存在久可以判断是否登录过。
一般我们选择存入 storage 中,因为 cookie 会在每次请求时,伴随发送。性能上没有 storage 好些。
下面是一个例子:
router.js
- import Vue from 'vue';
- import Router from 'vue-router';
- import LoginPage from '@/pages/login';
- import HomePage from '@/pages/home';
- import GoodsListPage from '@/pages/good-list';
- import GoodsDetailPage from '@/pages/good-detail';
- import CartPage from '@/pages/cart';
- import ProfilePage from '@/pages/profile';
- Vue.use(Router)
- const router = new Router({
- routes: [
- {
- path: '/', // 默认进入路由
- redirect: '/home' //重定向
- },
- {
- path: '/login',
- name: 'login',
- component: LoginPage
- },
- {
- path: '/home',
- name: 'home',
- component: HomePage
- },
- {
- path: '/good-list',
- name: 'good-list',
- component: GoodsListPage
- },
- {
- path: '/good-detail',
- name: 'good-detail',
- component: GoodsDetailPage
- },
- {
- path: '/cart',
- name: 'cart',
- component: CartPage
- },
- {
- path: '/profile',
- name: 'profile',
- component: ProfilePage
- },
- {
- path: '*', // 错误路由
- redirect: '/home' //重定向
- },
- ]
- });
- // 全局路由守卫
- router.beforeEach((to, from, next) => {
- console.log('navigation-guards');
- // to: Route: 即将要进入的目标 路由对象
- // from: Route: 当前导航正要离开的路由
- //如果 next 为空则路由正常进行跳转,如果 next 不为空,则进行跳转时,会中断
- const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile'];
- let isLogin = global.isLogin; // 是否登录,一般从 storage 中读取
- // 未登录状态;当路由到 nextRoute 指定页时,跳转至 login
- if (nextRoute.indexOf(to.name) >= 0) {
- if (!isLogin) {
- console.log('what fuck');
- router.push({ name: 'login' })
- }
- }
- // 已登录状态;当路由到 login 时,如果已经登录过,则跳转至 home
- if (to.name === 'login') {
- if (isLogin) {
- router.push({ name: 'home' });
- }
- }
- next();
- });
- export default router;