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

时间:2021-06-25 03:10:01

标签: javascript vue.js url nuxt.js nuxt-link

我想在浏览器的主页 /main 上存储我的网址,然后再使用 nuxt-link 转到另一个页面。这是我的nuxt-link

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

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

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

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

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

2 个答案:

答案 0 :(得分:0)

@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.
}

找到的文档链接 here

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

答案 1 :(得分:0)

如上所述,您确实可以使用一些路由器防护。
我确实更喜欢使用 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>