【问题标题】:how to call a function in vue when navigating way from route?从路线导航时如何在vue中调用函数?
【发布时间】:2020-11-21 12:52:21
【问题描述】:

当用户离开当前页面时,我试图调用一个清除本地存储的函数。我将如何做到这一点?我尝试使用 destroyed() 生命周期挂钩,但它不起作用。使用beforeRouteLeave() 会是一个很好的解决方案,我将如何在我的路由文件中实现它?

我的路线:

  {
    path: "/success",
    name: "Success",
    component: () =>
      import("../views/Success.vue"),
  },

我在当前成功页面上的钩子:

  destroyed() {
    window.localStorage.removeItem("intent");
  },

我对@9​​87654325@ 的尝试

  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


【解决方案1】:

您可以尝试为您设置(全局/页面)观察者,当您更改路由对象时会做一些事情

watch:{
    $route function(to, from){
        // do something
    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2022-07-18
    • 2021-01-06
    • 1970-01-01
    • 2020-10-16
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多