vue路由登录拦截(vue router登录权限控制)

实现原理:

哪些路由需要验证需要在路由文件router/index.js中指定:

    {
      path: '/',
      component: Home,
      name: 'Home',
      iconCls: 'fa fa-address-card',
      leaf: true,//只有一个节点
      children: [
          { 
            path: '/chart', 
            component: Chart, 
            name: 'Chart', 
            iconCls: 'el-icon-s-flag',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          }
      ]
    }

用户有没有登录需要给其指定状态,当用户登录了,我们用localStorage在Login.vue文件中为其状态指定为1:

            that.$axios({
              method: 'post',
              url: 'http://localhost:9999/article/check_login_status/',
              data: param
            })
            .then((res) => {
              if(res.data.ret){
                localStorage.setItem("islogin", 1); // 指定登录状态
                that.$router.push({path: "/table"});
              }else{
                that.$message('用户名或密码错误!');
                return false;
              }
            })
            .catch((e) => {
              console.log(err);
            });

退出时需要在Home.vue中为其指定状态为0:

localStorage.setItem("islogin", 0);

路由拦截需要用到导航守卫,关键代码如下:

router.beforeEach((to, from, next) => {
  let islogin = localStorage.getItem("islogin");
  islogin = Boolean(Number(islogin));

  if(to.path == "/login"){
    if(islogin){
      next("/table");
    }else{
      next();
    }
  }else{
    // requireAuth:可以在路由元信息指定哪些页面需要登录权限
    if(to.meta.requireAuth && islogin) {
      next();
    }else{
      next("/login");
    }
  }
})

全部代码:

router/index.js:

import Vue from 'vue'
import Router from 'vue-router'
const Home = () => import('@/components/HelloWorld')
const Badge = () => import('@/components/Badge')
const Progress = () => import('@/components/Progress')
const Table = () => import('@/components/Table')
const Tag = () => import('@/components/Tag')
const Chart = () => import('@/components/Chart')
const NotFound = () => import('@/components/NotFound')
const Login = () => import('@/components/Login')
const Tabs = () => import('@/components/Tabs')
const Rate = () => import('@/components/Rate')
const Form = () => import('@/components/Form')

Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/',
      component: Home,
      name: '导航一',
      iconCls: 'el-icon-s-flag',
      leaf: false,
      children: [
          { 
            path: '/tabs', 
            component: Tabs, 
            name: 'Tabs', 
            iconCls: 'el-icon-star-on',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          },
          { 
            path: '/rate', 
            component: Rate, 
            name: 'Rate', 
            iconCls: 'el-icon-star-on',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          }
      ]
    },
    {
      path: '/',
      component: Home,
      name: 'Home',
      iconCls: 'fa fa-address-card',
      leaf: true,//只有一个节点
      children: [
          { 
            path: '/badge', 
            component: Badge, 
            name: 'Badge', 
            iconCls: 'el-icon-s-help',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          }
      ]
    },
    {
      path: '/',
      component: Home,
      name: 'Home',
      iconCls: 'fa fa-address-card',
      leaf: true,//只有一个节点
      children: [
          { 
            path: '/table', 
            component: Table, 
            name: 'Table', 
            iconCls: 'el-icon-upload',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          }
      ]
    },
    {
      path: '/',
      component: Home,
      name: 'Home',
      iconCls: 'fa fa-address-card',
      leaf: true,//只有一个节点
      children: [
          { 
            path: '/tag', 
            component: Tag, 
            name: 'Tag', 
            iconCls: 'el-icon-s-cooperation',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          }
      ]
    },
    {
      path: '/',
      component: Home,
      name: 'Home',
      iconCls: 'fa fa-address-card',
      leaf: true,//只有一个节点
      children: [
          { 
            path: '/progress', 
            component: Progress, 
            name: 'Progress', 
            iconCls: 'el-icon-s-order',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          }
      ]
    },
    {
      path: '/',
      component: Home,
      name: 'Home',
      iconCls: 'fa fa-address-card',
      leaf: true,//只有一个节点
      children: [
          { 
            path: '/chart', 
            component: Chart, 
            name: 'Chart', 
            iconCls: 'el-icon-s-flag',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          }
      ]
    },
    {
      path: '/',
      component: Home,
      name: 'Home',
      iconCls: 'fa fa-address-card',
      leaf: true,//只有一个节点
      children: [
          { 
            path: '/form', 
            component: Form, 
            name: 'Form', 
            iconCls: 'el-icon-s-flag',
            meta: { // 在路由配置中加入meta:{requireAuth: true}
             requireAuth: true
            }
          }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      hidden: true,
      meta: { // 在路由配置中加入meta:{requireAuth: true}
       requireAuth: true
      }
    },
    {
      path: '*',
      hidden: true,
      redirect: { path: '/404' }
    },
    {
      path: '/404',
      hidden: true,
      name: '',
      component: NotFound
    }
  ]
})

export default router

router.beforeEach((to, from, next) => {
  let islogin = localStorage.getItem("islogin");
  islogin = Boolean(Number(islogin));

  if(to.path == "/login"){
    if(islogin){
      next("/table");
    }else{
      next();
    }
  }else{
    // requireAuth:可以在路由元信息指定哪些页面需要登录权限
    if(to.meta.requireAuth && islogin) {
      next();
    }else{
      next("/login");
    }
  }
})

Login.vue:





Home.vue:






django代码:views.py

@csrf_exempt
def check_login_status(request):
    return_dict = {"ret": False}

    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == 'admin' and password == '123456':
            return_dict['ret'] = True

    return HttpResponse(json.dumps(return_dict), content_type="application/json")

 

你可能感兴趣的:(vue)