vue?退出登錄?清除localStorage的問題
更新時間:2022年12月20日 14:30:56 作者:xiaodong_blogs
這篇文章主要介紹了vue?退出登錄?清除localStorage的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
vue 退出登錄 清除localStorage
在vue登錄的時候我們會保持狀態(tài) 如下:
methods: { login(){ this.axios.post('users/login/',this.form).then(res=>{ console.log(res.data) if(res.data.code == 200){ localStorage.setItem('userid',res.data.userid) localStorage.setItem('username',res.data.username) localStorage.setItem('mobile',res.data.mobile) this.$router.push({ name:'Index' }) } }) } },
此時 瀏覽器中會將狀態(tài)保存
當退出賬號 我們就需要 清除狀態(tài)保持
<template> <div> <a @click="exit" >退出</a> </div> </template> <script> import axios from 'axios' export default { props: { passUser:{ } }, data() { return { } }, methods: { exit(){ // 清除狀態(tài)保持 window.localStorage.clear() // 狀態(tài)保持清除后刷新頁面 window.location.reload() } }, created() { } } </script> <style scoped> </style>
vue 登錄后無操作半小時后自動清除登錄狀態(tài)
在項目的頁面入口文件App.vue文件中監(jiān)聽用戶最后一次操作鼠標、鍵盤或滾動事件:
<template> <div id="app"> <router-view /> </div> </template> <script> // 登錄狀態(tài)使用store插件保存在客戶端的localStorage中 import storage from 'store' export default { name: 'App', computed: { token () { return storage.get('TOKEN') }, uid () { return storage.get('UID') }, userInfo () { return storage.get('USER_INFO') } }, mounted () { document.onmousemove = this.debounce(this.resetStatus, 3000) document.onkeydown = this.debounce(this.resetStatus, 3000) document.onscroll = this.debounce(this.resetStatus, 3000) }, methods: { // 使用防抖,對于短時間內(此處是3s)連續(xù)觸發(fā)的事件,只執(zhí)行最后一次 debounce (fn, delay) { let timer = null return function () { if (timer) { clearTimeout(timer) } timer = setTimeout(fn, delay) } }, resetStatus () { // 重置store插件自動清除時間 if (this.token) { storage.set('TOKEN', this.token, new Date().getTime() + 30 * 60 * 1000) storage.set('UID', this.uid, new Date().getTime() + 30 * 60 * 1000) storage.set('USER_INFO', this.userInfo, new Date().getTime() + 30 * 60 * 1000) } } } } </script> <style lang="less" scoped> #app { min-height: 100vh; min-width: 1200px; margin: 0 auto; } </style>
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
如何封裝axios form-data針對統一的formData入參方式
這篇文章主要介紹了如何封裝axios form-data針對統一的formData入參方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05