公司为了配合等保,须要做一些安全性解决

例如:如果登录用户在进入零碎后,始终没有操作的状况下,一段时间后强制登出零碎

刚开始共事写了一个,思路是:

在拜访零碎登录页面的时候执行一个setInterval,每隔3秒钟去查看一遍是否超出咱们设定的工夫没有操作系统了,而且断定这个是拿mouseover来监听的鼠标是否来到最外层div

实现代码

//App.vue页面  // html  <div id="app" @mouseover="cmouseovered">    <router-view />  </div>    // js  mounted() {     this.tiemer = window.setInterval(this.checkTimeout, 3000)  },    methods: {    cmouseovered() {       localStorage.setItem('lastTime', new Date().getTime())    },    checkTimeout() {      this.currentTime = new Date().getTime() // 更新以后工夫      this.lastTime = localStorage.getItem('lastTime')      if (this.currentTime - this.lastTime > this.timeOut) {        // 判断是否超时        if (this.$route.path !== '/login') {          // console.log('超时了')          this.$store.dispatch('user/logout')          this.$router.push(`/login?redirect=${this.$route.fullPath}`)        }      }    }  }

这个思路,能够很显著看到几个问题:

  • 1.这个代码是写在VUE我的项目最外层 app页面,也就是还没登录的时候定时器曾经在执行了;登录页必定是不须要再退出零碎了
  • 2.定时器没有开释,setInterval是比拟耗费性能的
  • 3.比对的是本地工夫,本地机器工夫是能够随时批改的

联合这几个问题,咱们来做一下优化

  • 针对第一个问题,全局页面不止app一个,最好是放在登录当前的全局页面去监听事件,咱们我的项目有layout,所以把监听移植到layout比拟适合;
  • 针对第二个问题,应用setTimeout代替setInterval,性能更好
  • 针对第三个问题优化点:不去比照工夫,咱们只有做到再过多长时间执行退出零碎操作即可

最初实现代码

<div class="app-wrapper" @mouseover="cmouseovered"></div>// jsmounted() {    this.countTime()  },  methods: {    countTime() {      const vm = this      this.timer = setTimeout(function() {        vm.logout()      }, this.timeOut)    },    cmouseovered() {      clearTimeout(this.timer)      this.countTime()    },    async logout() {      await this.$store.dispatch('user/logout')      this.$router.push('/login')      clearInterval(this.tiemer)    }  }

这个实现就解决了下面3大问题,大家看到了,我用的是mouseover来监听用户还有没有操作系统,因为这个事件会冒泡到所有的下级元素,只有鼠标还有挪动在咱们的界面上,就每次都会重置定时器

❤️ 看完两件小事

如果你感觉这篇文章对你挺有启发,我想请你帮我两个小忙:

把这篇文章分享给你的敌人 / 交换群,让更多的人看到,一起提高,一起成长!

关注公众号 「画漫画的程序员」,公众号后盾回复「资源」 收费支付我精心整顿的前端进阶资源教程

JS中文网 - 前端进阶资源教程 www.javascriptC.com
一个致力于帮忙开发者用代码扭转世界为使命的平台,每天都能够在这里找到技术世界的头条内容