A shorthand to call same method in created and watch

Use a less known property called immediate to call a function during created and in watch.

Take the below scenario -

  • Component needs to fetch data from server to get contact detail when user clicks on a specific contact in a list
  • User can use arrow keys to fetch next or previous contact by clicking arrows on the component

One of the typical ways to address this requirement is to call the fetchContact method

  • in created to load data initially
  • and when arrow buttons are clicked (with a few params of course)
  • .. and when users click on the related contacts link below the main contact

The code will be something like -

created() {
    this.fetchContact(this.$route.params.id);
}

And..

watch: {
    route($route) {
        this.fetchContact($route.params.id);
    }
}

We would have been happy with the state of stuff as it is, but turns out we have a shortcut way of getting the same result.

Change the watch code to -

watch: {
    $route: {
        handler($route): {
            this.fetchContact($route.params.id);
        },
        immediate: true;
    }
}

You can remove code from created altogether.

Though this is technically a shorthand, I continue to use created or mounted since that way is more explicit and no one gets confused.

comments powered by Disqus