如何实现v-textarea无操作时2分钟后自动清空内容?
实现v-textarea无操作2分钟自动清空
可以通过监听输入事件+定时器的方式实现,具体步骤如下:
1. 定义核心数据
需要声明两个变量:
text:绑定v-textarea的内容timerId:存储定时器ID,用于后续重置和清除定时器
2. 编写定时器逻辑
- 每次输入内容时,先清除之前的定时器,再重新设置一个2分钟(120000毫秒)后触发的清空操作
- 定时器触发时,将
text置为空字符串
3. 组件销毁时清理定时器
避免组件销毁后定时器仍在运行造成内存泄漏
完整示例代码
<template> <v-textarea v-model.trim="text" clearable :label="modeLabel" @input="resetTimer" ></v-textarea> </template> <script setup> import { ref, onUnmounted } from 'vue' const text = ref('') const modeLabel = ref('输入内容') let timerId = null // 重置定时器 const resetTimer = () => { // 清除之前的定时器 if (timerId) clearTimeout(timerId) // 设置新的定时器,120秒后清空内容 timerId = setTimeout(() => { text.value = '' }, 120000) } // 组件销毁时清除定时器 onUnmounted(() => { if (timerId) clearTimeout(timerId) }) </script>
关键说明
@input事件会在用户输入、粘贴等操作时触发,确保每次操作都能重置定时器- 每次重置定时器前先执行
clearTimeout,避免多个定时器叠加导致提前清空 onUnmounted钩子中清除定时器,防止组件销毁后定时器仍占用资源
内容的提问来源于stack exchange,提问作者berkay gezbeli
相关产品推荐
相关产品推荐

