Ren
Ren

Reputation: 171

how to call a function in vue when navigating way from route?

I am trying to call a function that clears local storage when the user navigates away from the current page. How would I accomplish this? I tried using the destroyed() lifecycle hook but it did not work. Would using beforeRouteLeave() be a good solution and how would I implement that in my routes file?

my route:

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

my hook on the success page as it currently stands:

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

what i tried with beforeRouteLeave

  beforeRouteLeave: function(to, from, next) {
    window.localStorage.removeItem("intent");
    next();
  },

my mounted hook

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);
      });
  },

Upvotes: 3

Views: 1799

Answers (2)

Mykyta
Mykyta

Reputation: 170

You can try set (global/page) watcher for you, which will be do something when you route object changed

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

Upvotes: 1

Noah Bosman
Noah Bosman

Reputation: 1

mayby you can use the beforeDestroy() hook instead of the destroyed() hook.

Upvotes: 0

Related Questions