
本文介绍在 vue 3(options api)中,如何让 toggle 按钮在用户点击开启后,自动于 3 秒后恢复为关闭状态,并确保响应式更新与 dom 同步。
本文介绍在 vue 3(options api)中,如何让 toggle 按钮在用户点击开启后,自动于 3 秒后恢复为关闭状态,并确保响应式更新与 dom 同步。
在 Vue 3 使用 Options API 时,若希望 toggle 按钮具备“开启后自动关闭”的行为(例如防误触、临时激活等场景),关键在于:状态变更必须作用于响应式数据,并在正确的时机触发。你原代码中直接修改 compPropsVModelToggleClearDigitizedBtn 却未生效,很可能是因为该变量未被正确声明为响应式 data 属性,或其绑定未正确同步至组件内部状态。
以下是一个简洁、可靠且可直接运行的实现方案:
<template><div class="toggle-container">
<button :class="['toggle-btn', { 'active': isButtonActive }]" :aria-pressed="isButtonActive">
{{ isButtonActive ? 'ON (auto-off in 3s)' : 'OFF' }}
</button>
</div>
</template><script>
export default {
name: 'AutoOffToggleButton',
data() {
return {
isButtonActive: false,
};
},
methods: {
toggleButton() {
// 切换状态
this.isButtonActive = !this.isButtonActive;
// 若刚开启,则启动 3 秒自动关闭定时器
if (this.isButtonActive) {
setTimeout(() => {
// 确保组件仍存活(避免内存泄漏或警告)
if (this.$el) {
this.isButtonActive = false;
}
}, 3000);
}
},
},
};
</script><style scoped>
.toggle-btn {
padding: 8px 16px;
font-size: 14px;
border: none;
border-radius: 4px;
background-color: #e0e0e0;
cursor: pointer;
transition: background-color 0.2s;
}
.toggle-btn.active {
background-color: #42b883;
color: white;
}
</style>
✅ 核心要点说明:
vue-composition-api-best-practices
Vue 3 组合式 API 与
热门下载
相关下载
精品课程
相关推荐
/
热门推荐
/
最新课程
最新文章
