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