在使用 nuxt-link 进入新页面之前存储 url

storing url before going to new page with nuxt-link

我想在使用 nuxt-link 转到另一个页面之前,在浏览器的主页 /main 上存储我的 url。这是我的 nuxt-link:

<NuxtLink
  :to="`/search?param={number}`"
  @click.native="assignAddress"
>
  SEARCH
</NuxtLink>

这是点击nuxt-link触发的方法:

assignAddress() {
  localStorage.setItem("address", `${this.$route.path}`);
},

问题是它在浏览器中保存 /search。我认为发生的是在nuxt更改页面后触发了方法assignAddress

如何先在浏览器中存储 url,然后更改页面,以便在我的浏览器中存储 /main 而不是 /search

@seyet 你试试在 beforeRouteLeave 导航守卫中设置它怎么样。

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 找到文档 here

请务必在完成后致电 next()

如上所述,您确实可以使用一些路由器保护程序。
我确实更喜欢使用 beforeRouteEnter 而不是 beforeRouteLeave,因为我觉得如果我的目标组件正确安装,resolution flow 可能不太容易出错,因此在组件转换期间没有错误。

这是代码方面的样子

/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>