App.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <template>
  2. <div id="app">
  3. <router-view />
  4. </div>
  5. </template>
  6. <script>
  7. let timmer = null //超时退出 定时器 必须放到全局,解决vue数据同步导致无法清除定时器
  8. export default {
  9. name: 'App',
  10. data() {
  11. return {
  12. lastTime: null, //超时退出 最后时间
  13. }
  14. },
  15. created() {
  16. // 在页面加载时读取sessionStorage里的状态信息
  17. if (sessionStorage.getItem('store')) {
  18. this.$store.replaceState(
  19. Object.assign({},
  20. this.$store.state,
  21. JSON.parse(sessionStorage.getItem('store'))
  22. )
  23. )
  24. }
  25. // 在页面刷新时将vuex里的信息保存到sessionStorage里
  26. // beforeunload事件在页面刷新时先触发
  27. window.addEventListener('beforeunload', () => {
  28. sessionStorage.setItem('store', JSON.stringify(this.$store.state))
  29. });
  30. // 超时退出 start
  31. this.lastTime = new Date();
  32. window.addEventListener('resize', () => {
  33. if (timmer) {
  34. clearTimeout(timmer);
  35. }
  36. timmer = setTimeout(() => {
  37. if (this.$route.path != '/login') {
  38. this.currentTime();
  39. }
  40. }, 1000)
  41. })
  42. window.addEventListener('click', () => {
  43. if (timmer) {
  44. clearTimeout(timmer);
  45. }
  46. timmer = setTimeout(() => {
  47. if (this.$route.path != '/login') {
  48. this.currentTime();
  49. }
  50. }, 1000)
  51. })
  52. window.addEventListener('scroll', () => {
  53. if (timmer) {
  54. clearTimeout(timmer);
  55. }
  56. timmer = setTimeout(() => {
  57. if (this.$route.path != '/login') {
  58. this.currentTime();
  59. }
  60. }, 1000)
  61. }, true)
  62. window.addEventListener('mousemove', () => {
  63. if (timmer) {
  64. clearTimeout(timmer);
  65. }
  66. timmer = setTimeout(() => {
  67. if (this.$route.path != '/login') {
  68. this.currentTime();
  69. }
  70. }, 1000)
  71. }, true)
  72. // 超时退出 end
  73. },
  74. methods: {
  75. currentTime() { // 超时退出
  76. const currentTime = new Date();
  77. if (currentTime - this.lastTime > 1000 * 60 * 20) {
  78. this.lastTime = currentTime
  79. if (this.$route.path != '/login') {
  80. this.$message({
  81. message: '登录超时,将返回登录页',
  82. type: 'error',
  83. duration: 2000
  84. })
  85. setTimeout(() => {
  86. this.$store.dispatch('user/logout')
  87. this.$router.push(`/login?redirect=${this.$route.fullPath}`)
  88. }, 2000)
  89. }
  90. } else {
  91. this.lastTime = currentTime;
  92. }
  93. }
  94. }
  95. }
  96. </script>