登录拦截功能实现步骤

225 阅读2分钟

1769.jpg_wh1200.jpg 小编在掘金的第一天: 今天我们来讲述一下有关登录一个网页需要注意的一个安全问题,登录任何一个网页都有自己的安全保护措施,规定用户一定要在满足登录条件的情况下才可以成功登录,访问到自己所能看到的页面!

实现步骤如下:

1.在所创建的项目中找到router下面的index.js进行操作 1.png

 判断是否需要登录的核心在: meta: {
      requiresAuth: true, //设置为需要登录
      requiresAuth该名可以自定义名称 后面的true和fasle分别代表进入该页面用户是否需要去登录
      【true为需要登录  false为不需要登录】
    },

具体操作案例如下:

【需要注意点的点在登录页面则不需要登录直接设置为false即可】
const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
    redirect: "/login",
  },
  {
    path: "/about",
    name: "about",
    component: () => import("../views/AboutView.vue"),
    meta: {
      requiresAuth: true, //设置为需要登录
    },
    children: [
      {
        path: "/about/detail",
        name: "详情页",
        component: () => import("../views/detailView.vue"),
        meta: {
          requiresAuth: true, //设置为需要登录
        },
      },
      {
        path: "/about/index",
        name: "",
        component: () => import("../views/indexView.vue"),
        meta: {
          requiresAuth: true, //设置为需要登录
        },
      },
      {
        path: "/about/banner",
        name: "",
        component: () => import("../views/bannerView.vue"),
        meta: {
          requiresAuth: true, //设置为需要登录
        },
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/loginView.vue"),
    // 【*】
    meta: {
      requiresAuth: false, //设置为false不需要登录
    },
  },
  {
    path: "/detail",
    name: "detail",
    component: () => import("../views/detailView.vue"),
    meta: {
      requiresAuth: true, //设置为需要登录
    },
  },
];

2.实现真正的登录拦截

其中的关键词是一个【token该名可自定义主要用于判断用户是否进行成功登录,是否需要拦截,有的话可以成功进行访问该页面,若没有则跳转到登录页】

若没有固定在登录页

bb.png

// 登录拦截
router.beforeEach((to, from, next) => {
  // console.log(to.matched); //是一个数组
  if (to.matched.some((item) => item.meta.requiresAuth)) {
    // to.matched.some((item) => item.meta.requiresAuth)的结果是一个true或者fasle
    // 需要登录
    // 跳转到登录页
    let token = localStorage.getItem("token");
    if (token) {
      next();
    } else {
      next("/login");
    }
  } else {
    // 否则进入页面
    next();
  }
});

若成功则成功进入页面【效果如下】

cc.png

!!!新手小白上路 多多指点改正 以上代码仅供参考