Reputation: 4280
I am able to use this.$router.go(-1)
to redirect a user to the previous route. However, I am not able to understand how I get get the information about the previous route before redirecting.
Basically, by first reading what the previous route was, I want to make sure that the previous route was from the same domain and only then redirect to it, otherwise do something else.
Upvotes: 11
Views: 31459
Reputation: 2089
In the [middleware] directory you can put this script [routing.js]:
/* eslint-disable no-undef */
/* eslint-disable no-console */
export default function (context) {
// current route
console.log('route=', context.route.name)
// previous route
if (process.client) {
const from = context.from
console.log('from=', from)
}
}
In [nuxt.config.js]:
router: {
...
middleware: 'routing'
},
Whenever you change the current page in the client you should see a log showing the previous page. Maybe it can help you.
Upvotes: 2
Reputation: 2164
In your page you can add asyncData
hook which have access to context
object with from
property:
asyncData({ from }) {
console.log(from);
}
Upvotes: 7
Reputation: 2948
You can achieve this by implementing the Vue Navigation guards, on the component/page.
<script>
export default {
beforeRouteEnter(to, from, next) {
console.log(from)
next()
},
data() {
return {
...
prevRoute: null,
}
}
}
</script>
Or there is this guy https://gist.github.com/zolotyx/b4e7fda234b3572fb7adaf11391f8eef#file-auth-js, he has made a script to help in redirecting
Upvotes: 4
Reputation: 586
in nuxt static methods where you have access to nuxt context ex: asyncData or middlewares
:
asyncData({from}){
// do something with from
}
but if you want to get the prev route in vue instance you can use
this.$nuxt.context.from
also, remember that from
can be undefined if there wasn't any prev page in the browser history
Upvotes: 12
Reputation: 14201
There is no out of the box way to get this information.
What you can do is attach a beforeRouteEnter
as a global guard and save the route before navigating to a new route.
Then you can check to see if there is a previous route saved and execute this.$router.go(-1)
If you are using the router in history
mode you could be tempted to use the History
api that vue-router is using to get this information. But HistoryApi doesn't allow for this as this would be a huge privacy problem. You could see the entire history of the user in the current tab.
Upvotes: 3