How to check if I'm coming from a "direct" routing and not from a "back" routing?

Viewed 19

It's basically a simple task: I'm using Vue3 with the Vue Router, there's my Home.vue component which lives in the / route, then there's a ProductDetails.vue component which lives in the /product route.

I want to execute a certain action when the user is navigating to my / route. However, I only want this action to happen when the user directly navigates here, meaning via clicking a link or via the browser's URL bar. I don't want the action to execute when he is navigating back from ProductsDetails.vue (or routing via "back" from anywhere, for that matter).

How do I achieve this with Vue3 or Vue Router methods? I know I can probably do it with query parameters in my URL but I'd prefer not to.

1 Answers

You could use in-component navigation guards (read more about it here (options api) OR here (composition api))

Your code could look something like this

...
beforeRouteEnter(to, from, next) {
 if(from.path === '/') {
   // do something
 }
},
...
Related