Categories
Vue Answers

How to use Vue Router beforeRouteEnter to trigger method in a Vue.js single file component?

Spread the love

Sometimes, we want to use Vue Router beforeRouteEnter to trigger method in a Vue.js single file component.

In this article, we’ll look at how to use Vue Router beforeRouteEnter to trigger method in a Vue.js single file component.

How to use Vue Router beforeRouteEnter to trigger method in a Vue.js single file component?

To use Vue Router beforeRouteEnter to trigger method in a Vue.js single file component, we can call our method in the next callback.

For instance, we write

<script>
export default {
  //...
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.initializeSearch();
    });
  },
  //...
};
</script>

to call the initializeSearch method when the beforeRouterEnter is done running by calling next with a callback that calls the method.

vm is the component instance that has the initializeSearch method.

Conclusion

To use Vue Router beforeRouteEnter to trigger method in a Vue.js single file component, we can call our method in the next callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *