vue实现锁屏
Vue 实现锁屏功能
锁屏功能通常用于在特定条件下阻止用户与页面交互,常见于后台管理系统或需要临时阻止操作的应用场景。以下是基于 Vue 的实现方案:
锁屏组件实现
创建锁屏组件 LockScreen.vue,包含蒙层和密码输入框:
<template>
<div v-if="isLocked" class="lock-screen">
<div class="lock-mask"></div>
<div class="lock-content">
<h3>系统已锁定</h3>
<input
v-model="password"
type="password"
placeholder="请输入解锁密码"
@keyup.enter="unlock"
/>
<button @click="unlock">解锁</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isLocked: false,
password: ''
}
},
methods: {
lock() {
this.isLocked = true
this.password = ''
},
unlock() {
if (this.password === '预设密码') {
this.isLocked = false
this.$emit('unlocked')
} else {
alert('密码错误')
}
}
}
}
</script>
<style scoped>
.lock-screen {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
}
.lock-mask {
position: absolute;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
.lock-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border-radius: 5px;
text-align: center;
}
</style>
全局状态管理
使用 Vuex 管理锁屏状态:

// store/modules/lock.js
export default {
state: {
isLocked: false
},
mutations: {
SET_LOCK(state, status) {
state.isLocked = status
}
},
actions: {
lock({ commit }) {
commit('SET_LOCK', true)
},
unlock({ commit }) {
commit('SET_LOCK', false)
}
}
}
自动锁屏功能
实现无操作自动锁屏逻辑:
// utils/autoLock.js
let timer = null
const timeout = 30 * 60 * 1000 // 30分钟
export function setupAutoLock(store) {
window.addEventListener('mousemove', resetTimer)
window.addEventListener('keypress', resetTimer)
function resetTimer() {
clearTimeout(timer)
timer = setTimeout(() => {
store.dispatch('lock/lock')
}, timeout)
}
resetTimer()
}
路由守卫控制
在路由跳转时检查锁屏状态:

// router/index.js
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && store.state.lock.isLocked) {
next({ path: '/unlock' })
} else {
next()
}
})
实际应用示例
在 App.vue 中使用锁屏组件:
<template>
<div id="app">
<router-view/>
<lock-screen
v-if="$store.state.lock.isLocked"
@unlocked="$store.dispatch('lock/unlock')"
/>
</div>
</template>
<script>
import LockScreen from '@/components/LockScreen'
import { setupAutoLock } from '@/utils/autoLock'
export default {
components: { LockScreen },
created() {
setupAutoLock(this.$store)
}
}
</script>
增强安全性
- 密码加密存储,避免明文保存
- 添加错误次数限制,防止暴力破解
- 记录锁屏日志,包括锁定时间、解锁尝试等
- 考虑添加二次验证机制
移动端适配
针对移动设备添加触摸事件支持:
window.addEventListener('touchstart', resetTimer)
调整锁屏组件样式,确保在移动设备上正常显示:
@media (max-width: 768px) {
.lock-content {
width: 80%;
}
}
以上方案提供了完整的锁屏功能实现,可根据实际需求调整超时时间、密码验证方式等细节。






