lab006: Composables, Composition, and vueUse
July 29, 2022
Interval fired: 0
In the demo above, I used the composable function useInterval, one of many such utilities available freely from vueUse.org. We’ll explore this utility to give you a sense of how vueUse composables give you both power and control when it comes to doing stuff on the web.
To import useInterval, you must first install vueUse (
npm i @vueuse/core
).
The useInterval function takes in a number as a parameter, which sets the interval. In this lab I set the interval to 200ms.
<script setup>
import { useInterval } from '@vueuse/core'
const { counter, pause, resume } = useInterval(200)
</script>
<template>
<p>
Interval fired: {{ counter }}
</p>
<button @click="pause()">
pause
</button>
<button @click="resume()">
resume
</button>
<button @click="counter = 0">
reset
</button>
</template>
<script setup>
import { useInterval } from '@vueuse/core'
const { counter, pause, resume } = useInterval(200)
</script>
<template>
<p>
Interval fired: {{ counter }}
</p>
<button @click="pause()">
pause
</button>
<button @click="resume()">
resume
</button>
<button @click="counter = 0">
reset
</button>
</template>
We receive the properties counter, pause, and resume
from the return of the useInterval function. The counter starts counting off automatically (I assume this can be configured otherwise; there is an “options” object that can be passed into useInterval as a second argument. Documentation is here).
Lastly, I wired up some buttons that invoke the pause and resume functions that we so conveniently received from useInterval(). And since the counter variable is already reactive, the last button can reset its value to 0 on user click and the UI will automatically update .
Key Takeaway
Why bring in useInterval from vueUse rather than “roll your own” interval function using the native setTimeout function (which useInterval utilizes under the hood)?
For one thing, you get reactivity. Notice how I was able to change the value of counter
and the UI/template reacted to it. In addition, you get the pause
and resume
functions that abstract away the details of the setTimeout api and allow you to perform often-complex functionality with a simply import and execution.
And we’ve only begun to explore the useInterval API. Perhaps there are more treasures to be found!
This was just an introduction to the vueUse library. Stay tuned for more exciting vueUse utility discovery expeditions! DannyDevs, out!