问题
I am building a cordova Vue app. In many cases there is deeper links like this
/profile/:id/:contact_type/contacts:contact_id
Where you would first be on /profile/:id
and then click a link to go to /profile/:id/:contact_type/contacts:contact_id
The standard router.go(-1)
works fine if you were on the profile page first. But if you get a notification or something, and are sent from any page, for example /settings/:id
. Your back button should behave more like an Up button, pressing back on /profile/:id/:contact_type/contacts:contact_id
should take you to /profile/:id
and not /settings/:id
.
How do I set this up? I tried a few things like splitting the current route on /
and popping it, then joining back and pushing to that. But that doesn't work with parameters, especially if there is more than 1.
const path = router.currentRoute.path
const URLSplit = path.split('/')
URLSplit.length = URLSplit.length - 1
const newTarget = URLSplit.join('/')
if (newTarget) {
router.push(newTarget)
} else {
router.push('/home')
}
I also tried using child routes, but that requires a router-view
in each page, which isn't what I want to do.
I have already captured the back button operation, I just want to know if there is a way to set up Vue to do this sort of back operation, or is there a way I am supposed to set up the router to do this, or a function that can figure out the current route and go up to it?
回答1:
That sounds like it would defeat the original purpose of navigating between historical/visited pages (rather than going up one level in the routes).
I would instead add a dedicated, in-app back button for this (like Google apps do have one); otherwise, you might have to try and intercept the browser's default behavior for that particular button, by listening to the popstate event of the Window
interface which is fired when the active history entry changes. But if you have to, there is a workaround for that with Global Before (navigation) Guards.
With an in-app back (or technically "up") button I mentioned earlier, you could use In-Component Guards.
For example, given the following routes
settings...
const router = new Router({
mode: 'history',
routes: [
{
path: '/profile/:id',
name: 'profile',
component: Profile,
children: [{
path: ':contact_type/contacts:contact_id',
name: 'contact',
component: Contact
}]
}
]
})
...you would directly define the route navigation guards inside the route component (e.g. Contacts.vue
):
<template>
<div>
<router-link :to="{ name: 'profile' }"><- back to profile</router-link>
Some contact information.
</div>
</template>
<script>
export default {
beforeRouteLeave(to, from, next) {
if (from.name === 'contact' && to.name !== 'profile') {
next({
name: 'profile',
params: {
id: from.params.id
}
});
}
else {
next();
}
}
}
</script>
Not necessarily the best approach, but that should work.
来源:https://stackoverflow.com/questions/56331630/how-to-set-up-vue-routes-or-override-back-button-to-function-like-an-app