登录登出拦截及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     },   },

退出按钮

 退出    logout() {       window.localStorage.clear();       this.$router.push("/login");     }, TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
Bing Webmaster Portal Back