This page looks best with JavaScript enabled

A shorthand to call same method in created and watch

 ·   ·  ☕ 2 min read

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 -

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

And..

1
2
3
4
5
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 -

1
2
3
4
5
6
7
8
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things