【发布时间】:2020-11-21 12:52:21
【问题描述】:
当用户离开当前页面时,我试图调用一个清除本地存储的函数。我将如何做到这一点?我尝试使用 destroyed() 生命周期挂钩,但它不起作用。使用beforeRouteLeave() 会是一个很好的解决方案,我将如何在我的路由文件中实现它?
我的路线:
{
path: "/success",
name: "Success",
component: () =>
import("../views/Success.vue"),
},
我在当前成功页面上的钩子:
destroyed() {
window.localStorage.removeItem("intent");
},
我对@987654325@ 的尝试
beforeRouteLeave: function(to, from, next) {
window.localStorage.removeItem("intent");
next();
},
我的挂载钩
let intent = window.localStorage.getItem(intent);
// const product = window.localStorage.getItem(product);
axios
.get("http://localhost:5000/pay/confirm", {
params: {
intent: intent
}
})
.then(res => {
console.log(res.data.status);
if (res.data.status == "succeeded") {
console.log(res.data.status);
this.confirmPayment();
} else {
this.paid = false;
}
console.log(this.item);
});
},
【问题讨论】:
-
destroyed钩子究竟如何不适合您?如果你真的离开了它,这个特殊的钩子应该会触发,beforeRouteLeave。 -
这可能与我挂载的钩子有关,我将其添加到问题中。但在我看来,当导航回页面时,get 请求不应该通过,因为在导航离开时,意图已从本地存储中删除。当我在控制台中注销 localStorage 时,Intent 不在对象中。所以我不明白为什么我的获取请求仍在进行中。
-
澄清一下,当您说“当用户离开当前页面时”,他们是从
Success.vue导航离开,还是到 它? -
他们正在从 success.vue 导航到我网站中的任何其他路线。
-
@Ren 似乎没有任何
if检查会阻止mounted上的GET 请求。
标签: vue.js vue-router