Vue-router: Resolve promise in a redirect method

Created on 30 Oct 2017  路  4Comments  路  Source: vuejs/vue-router

What problem does this feature solve?

I have a site with 3 router views and I want to persist the last view if they land on '/'

My application already uses localforage for client-side caching and ideally, I would like to use it for this too, but their api is built on promises, which doesn't seem to be handled in redirect functions in a vue-router config.

For example:

Explicitly visiting '/a', '/b' or '/c' loads the respective views. But visiting '/' will check localforage for the last view, else will return a default ('a' in the example below.)

What does the proposed API look like?

{
  path: '/'
  redirect: () => localforage.get('some-key').then(data => { name: data || 'a' })
}

Most helpful comment

just use a beforeEnter Guard.

{
  path: '/'
  beforeEnter: (to, from, next) => {
    localforage.get('some-key')
      .then(data => next({ name: data || 'a' }))
  }
}

All 4 comments

just use a beforeEnter Guard.

{
  path: '/'
  beforeEnter: (to, from, next) => {
    localforage.get('some-key')
      .then(data => next({ name: data || 'a' }))
  }
}

Ah perfect, thanks.

@LinusBorg Your solution doesn't seem to work with redirects in child routes. beforeEnter doesn't seem to be called in child routes and even if you add the beforeEnter to the parent route, the child redirect function seems to be called before the parent beforeEnter function is called/resolved. Am I missing something?

EDIT: Work around is to put the redirect logic directly in the parent beforeEnter function. It may take a few more lines to conditionally match the to.path to the child route you want, but it works!

For vue-router 3.1.3, if you call next() in a promise resolution in beforeEnter, then you will have problems in the page: this.$router, this.$route won't be accessible, and many errors poping in the console...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Atinux picture Atinux  路  3Comments

yyx990803 picture yyx990803  路  3Comments

mitar picture mitar  路  3Comments

shinygang picture shinygang  路  3Comments

marcvdm picture marcvdm  路  3Comments