vue 退出登录 清除localStorage的问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue 退出登录 清除localStorage的问题

xiaodong_blogs   2022-12-20 我要评论

vue 退出登录 清除localStorage

在vue登录的时候我们会保持状态 如下:

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'
                    })
                }
            })
        }
    },

此时 浏览器中会将状态保存

当退出账号 我们就需要 清除状态保持

<template>
	<div>
		<a @click="exit" >退出</a>
	</div>
</template>
<script>
import axios from 'axios'
export default {
    props: {
        passUser:{

        }
    },
    data() {
        return {

        }
    },
    methods: {
        exit(){
        	// 清除状态保持
            window.localStorage.clear()
            // 状态保持清除后刷新页面
            window.location.reload()

        }
    },
    created() {

    }
}
</script>

<style scoped>

</style>

vue 登录后无操作半小时后自动清除登录状态

在项目的页面入口文件App.vue文件中监听用户最后一次操作鼠标、键盘或滚动事件:

<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
// 登录状态使用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)连续触发的事件,只执行最后一次
    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>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们