How to use routing guards in vue to achieve login ideas? ?

Ideas:
1. Set the routing for the component of our login page, and set a meta attribute value to record the existence of the token value
2. Set the router in main.js, beforeEach set the global routing guard, click when you log in The token value is stored in localStorage
3. If localStorage obtains the token value, let him enter the page where he wants to log in, otherwise he will be prevented from entering

  • routing
{
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      // 设置路由元数据
      Authorition: true
    },
},
{
    path: '/login',
    name: 'Login',
    component: Login
  }

main.js

router.beforeEach((to, from, next) => {
  console.log('to', to)
  const token = localStorage.getItem('token')
  if (to.meta.Authorition) {
    if (token) {
      next()
    } else {
      router.push({ name: 'Login' })
    }
  } else {
    next()
  }
})

log in page

 goLogin() {
      this.$refs["login_form"].validate(async valid => {
        //表单通过validate方法实现整体表单,其中valid为true代表所有验证规则通过,否则报错
        if (valid) {
          //调用封装的login方法
          const result = await login(this.ruleForm);
          let { flag } = result;
          console.log(flag)
          if (flag === 2) {
            //登录成功,则中转回上次访问的页面
            this.$router.push('/home');
          }
        } else {
          //登录失败,给出失败的提示
          return false;
        }
      });
    }

Note: The
token is worth getting when you log in. If you encapsulate axios, you need to get the token and set the request header in the request interception according to your needs.

Other:
What is the token value?
The token is actually more popular and can be called a secret code. Before some data is transmitted, the secret code must be checked first. Different secret codes are authorized for different data operations.

Token is worth knowing: https://www.jianshu.com/p/a2868b27675c

Guess you like

Origin blog.csdn.net/lqlq54321/article/details/106801152