Skip to content

Provide access to the router instance and component options in "beforeRouteEnter" guard #3166

Open
@bponomarenko

Description

@bponomarenko

What problem does this feature solve?

There are some use cases, when it is required to have access to the router instance and component options inside beforeRouteEnter guard. While beforeRouteUpdate and beforeRouteLeave could get such access through this.$router and this.$options, it seems not way to achieve it in beforeRouteEnter. Importing router instance (similar to store import suggestion here) is not an option for us because we have shared set of router components, which are re-used in different vue applications, so there is no single place to import vuex store from.

Use case

I'm trying to create generic plugin for our applications which will define hook to pre-load data. In some component data pre-load will happen via vuex store, so it should be accessible in this hook.

Here is simplified code for the plugin:

export default function install(Vue) {
  Vue.mixin({
    async beforeRouterEnter(to, from, next) {
      if (componentOptions.preloadData) {
        try {
          const nextCallbackParam = await componentOptions.preloadData.call(null, router.app.$store);
          next(nextCallbackParam);
        } catch (error) {
          // Custom error for a generic error handler
          next(new DataPreloadError(error));
        }
      } else {
        next();
      }
    },
  });
};

This plugin will make it possible to define custom preloadData() { ... } component option for a generic data pre-load as part of routing process. The only missing references to make it work are componentOptions and router.

Note that it is possible to provide router access in this particular example by passing it as plugin argument – export default function install(Vue, router) { ... }. However, it might be still beneficial to have access to router in the beforeRouteEnter guard, as it will be a solution for #3157.

What does the proposed API look like?

Proposal is to add additional guardContext argument to the guard function:

beforeRouteEnter(to, from, next, context) {
 // where context is { router: ..., componentOptions: ... }
}

However if it should be implemented in different way – would be great to hear it.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions