- src文件夹下新建judge文件夹
- 在judge文件夹下新建storage.js
export default {
setItem (key, value) {
value = JSON.stringify(value)
window.localStorage.setItem(key, value)
},
getItem (key, defaultValue) {
let value = window.localStorage.getItem(key)
// try {
value = JSON.parse(value)
// } catch {}
return value || defaultValue
},
removeItem (key) {
window.localStorage.removeItem(key)
},
clear () {
window.localStorage.clear()
}
}
- 在judge文件夹下新建astrict.js
// 引入路由和storage工具函数
import storage from '@/judge/storage'
import router from '@/router'
let lastTime = new Date().getTime()
let currentTime = new Date().getTime()
let timeOut = 30 * 60 * 1000 // 设置超时时间: 30分钟
window.onload = function () {
window.document.onmousedown = function () {
storage.setItem('lastTime', new Date().getTime())
}
}
function checkTimeout () {
currentTime = new Date().getTime() // 更新当前时间
if (currentTime - lastTime > timeOut) { // 判断是否超时
// 清除storage的数据(登陆信息和token)
storage.clear()
// 跳到登陆页
console.log(router)
if (router.history.current.fullPath !== '/') {
router.push({ name: '/' })
window.location.reload()
} // 当前已经是登陆页时不做跳转
}
}
export default function () {
/* 定时器 间隔30秒检测是否长时间未操作页面 */
window.setInterval(checkTimeout, 30000)
}
- 在main.js中引入
import Astrict from '@/judge/astrict'
Vue.use(Astrict)
5.重启
npm run dev