Vue 保存登录状态和拦截器的使用

登录状态

sessionStorage可以换成localStorage

存储
_this.username为需要保存的值的变量名

sessionStorage.setItem('username', _this.username);

获取

<span>{{getUserName}}span>
data() {
  return {
    username: '',
  }
},
computed: {
  getUserName() {
    this.username = sessionStorage.getItem('username');
    return this.username;
  }
},

 

拦截器

router =》index.js

import Vue from 'vue'
import Router from 'vue-router'
import Index from '../components/main/Index'
import PersonalInfo from "../components/user/PersonalInfo";
import Login from "../components/login/Login";

Vue.use(Router);
export default new Router({
  routes: [
    {
      path: '/index',
      name: 'index',
      component: Index
    },
    {
      path: '/personalInfo',
      name: 'personalInfo',
      component: PersonalInfo,
      requireAuth: true,   // 添加该字段,表示进入这个路由是需要登录的
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
  ]
})

main.js

// 拦截器
router.beforeEach((to, from, next) => {
  if (!to.path.startsWith('/personalInfo')) {  // 需要拦截的路由
    next()
  } else {
    let user = window.sessionStorage.getItem('username');
    if (!user) {
      next({
        path: '/login'
      })
    } else {
      next()
    }
  }
});

你可能感兴趣的:(Vue)