其他分享
首页 > 其他分享> > 登录登出拦截及vue控制用户信息localStorage

登录登出拦截及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() {       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  
TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:vue,登出,window,state,localStorage,user,router,store
来源: https://www.cnblogs.com/lyj0810/p/16312848.html