Reputation: 1150
I want to store my url when I am on the main page /main
in the browser before going to another page using nuxt-link
. This is my nuxt-link
:
<NuxtLink
:to="`/search?param={number}`"
@click.native="assignAddress"
>
SEARCH
</NuxtLink>
And this is the method that is triggered by clicking on nuxt-link
:
assignAddress() {
localStorage.setItem("address", `${this.$route.path}`);
},
The issue is that it saves /search
in the browser. What I think happens is that the method assignAddress
is being triggered after nuxt changes the page!
How can I store the url in the browser first and then change the page so in my browser I store /main
instead of /search
?
Upvotes: 1
Views: 2229
Reputation: 46604
As mentionned above, you can indeed use some router guards.
I do prefer to use beforeRouteEnter
over beforeRouteLeave
because I feel like the resolution flow may be less bug-prone if my targeted component is properly mounted, hence no bug during the component transition.
Here how this would look like code-wise
/pages/search-page.vue
<template>
<div>This is the search page</div>
</template>
<script>
export default {
name: 'SearchPage',
beforeRouteEnter(to, from, next) {
console.log('came from', from)
localStorage.setItem('address', from.path)
next()
},
}
</script>
Upvotes: 1
Reputation: 1920
@seyet how about you try setting it within the beforeRouteLeave
navigation guard.
beforeRouteLeave(to, from, next) {
// called when the route that renders this component is about to
// be navigated away from.
// has access to `this` component instance.
}
Link to docs found here
Just make sure to call next()
once you're finished.
Upvotes: 1