I have a v-textarea, I write something to area and if I do not any action, in v-textarea context must be cleared automatic after a certain time (2 minutes). How can I do it?
<v-textarea
v-model.trim="text"
clearable
:label="modeLabel"
>
I have a v-textarea, I write something to area and if I do not any action, in v-textarea context must be cleared automatic after a certain time (2 minutes). How can I do it?
<v-textarea
v-model.trim="text"
clearable
:label="modeLabel"
>
CodePudding user response:
I would do something like this with a timer.
<v-textarea
v-model.trim="text"
clearable
:label="modeLabel"
@change="clearHandler(event)"
>
var timerID = null;
function clearHandler() {
if (timerID) {
clearTimeout(timerID);
}
// create a timer to clear the textarea by setting the model to empty string
timerID = setTimeout(() => {
this.text = "";
}, 120000);
}
Also, I would use this.timerID
or a ref
variable, instead of var
like my example, depending on what version of vue you are using.
CodePudding user response:
I've created this with a simple watcher. First, we create a function that includes the timeout. After that we create a watcher triggered to val
. In this watcher, we call the timeout and after that clear the timeout. The reason for this is that we want it to re-run the function. The watcher also watches the value, if the user enters sth, the timeout will be canceled.
new Vue({
el: "#app",
data() {
return {
val: ''
}
},
methods: {
timeout() {
return setTimeout(() => {
this.val = ''
}, 5000)
}
},
watch: {
val: {
handler() {
this.timeout()
clearTimeout(this.timeout);
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input v-model="val" />
</div>