Skip to content

Vue Composition API: Watchers

Declan Coughlan edited this page May 30, 2023 · 3 revisions

Class Component

import { Watch } from "vue-property-decorator";
    @Watch("ticketIsProcessed")
    private onTicketIsProcessedChanged(value: boolean): void {
        if (value) {
            this.redirect();
        }
    }

Composition API

import { watch } from "vue";
watch(ticketIsProcessed, (value: boolean) => {
    if (value) {
        redirect();
    }
});

When watching complex objects, and the trigger should only be attached to changes of a particular property, such as route.value.query when using useRoute(). You can use a resolver function to target the property you're interested in watching.

watch(
  () => route.value.query,
  (value) => {
    if (value.registration === "success") {
      router.replace({ query: {} });
      appTourComponent.value?.showModal();
    }
});

Documentation

Clone this wiki locally