VueNuxtViteVueTips & Tricks

Curated collection of practical tips, tricks and best practices for building modern Vue applications.

Vue 3.5's `onWatcherCleanup()` lets you register cleanup callbacks inside watchers — perfect for aborting stale API requests.

<script setup>
import { ref, watch, onWatcherCleanup } from 'vue'

const userId = ref(1)

watch(userId, (newId) => {
  const controller = new AbortController()

  fetch(`/api/users/${newId}`, { signal: controller.signal })
    .then(r => r.json())
    .then(data => { /* handle data */ })

  // If userId changes before fetch completes, abort the previous request
  onWatcherCleanup(() => {
    controller.abort()
  })
})
</script>
<!-- Also works inside watchEffect -->
<script setup>
import { ref, watchEffect, onWatcherCleanup } from 'vue'

const searchQuery = ref('')

watchEffect(() => {
  const controller = new AbortController()

  fetch(`/api/search?q=${searchQuery.value}`, {
    signal: controller.signal
  })
    .then(r => r.json())
    .then(data => { /* update results */ })

  onWatcherCleanup(() => controller.abort())
})
</script>