Sometimes, we want to use setTimeout to run code after a delay with Vue.js.
In this article, we’ll look at how to use setTimeout to run code after a delay with Vue.js.
Use setTimeout with Vue.js
We can use setTimeout
with Vue.js by passing in an arrow function as an argument into it.
For instance, we can write:
<template>
<div id="app">
<button @click="setShow">show</button>
<p v-if="show">hello</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
show: false,
};
},
methods: {
setShow() {
setTimeout(() => {
this.show = true;
}, 2000);
},
},
};
</script>
We have the setShow
method that calls setTimeout
with an arrow function that calls this.show
to true
as the first argument.
The 2nbd argument is the delay before running the callback in the first argument in milliseconds.
We’ve to use an arrow function to get the right value of this
in the callback function.
this
show be the component instance since arrow functions don’t bins to their value of this
.
We set setShow
as the value of the @click
directive to run it when we click the button.
So when we click it, the div shows since show
becomes true
.
Conclusion
We can use setTimeout
with Vue.js by passing in an arrow function as an argument into it.