登录登出拦截及vue控制用户信息localStorage

"store": "^2.0.12",

main.js  引入store

import store from "./store";

Vue.prototype.$axios = axios;
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {// 判断跳转的路由是否需要登录
    if (store.state.user.username) {// vuex.state判断user.username是否存在
      next()// 已登录
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }// 将跳转的路由path作为参数
      })
    }
  } else {
    next()
  }
}
)
new Vue({
  router,
  axios,
  store,
  render: h => h(App)
}).$mount('#app')

 

 

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {
      username: window.localStorage.getItem('user' || '[]') == null ? '' : JSON.parse(window.localStorage.getItem('user' || '[]')).username
    }
  },
  mutations: {
    login(state, user) {
      state.user = user
      // 存储到session
      window.localStorage.setItem('user', JSON.stringify(user))
    }
  },


  actions: {
  },
  modules: {
  }
})

router/index.js需要拦截的router

 
{
    path: '/home',
    component: Home,
    hidden: true,
    meta: {
  /*拦截设置*/
      requireAuth: true,
      keepAlive: false
    },
  },

退出按钮

 <el-button type="info" @click="logout">退出</el-button>
 
logout() {
      // 这里需要elementui的支持,如果使用其他界面组件自行替换即可
      this.$confirm("正在离开本页面,本页面内所有未保存数据都会丢失", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //清除用户缓存
        window.localStorage.clear();
        this.$router.push("/login");
      });
    },

 
posted @ 2022-05-26 11:24  快了星球  阅读(139)  评论(0)    收藏  举报