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.)
{
path: '/'
redirect: () => localforage.get('some-key').then(data => { name: data || 'a' })
}
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...
Most helpful comment
just use a
beforeEnterGuard.