Anar Salimkhanov
Anar Salimkhanov

Reputation: 837

Adding default query to all router links in Vue?

I'm trying to find a way to add default query to all router-links on a page (in all components that it has)?

For example, I want all links on a page to end with argument: utm_campaign=from_our_friends.

And this page uses components that are also used by other pages.

Upvotes: 1

Views: 120

Answers (2)

Anar Salimkhanov
Anar Salimkhanov

Reputation: 837

Based on the answer by @Majed Badawi, I ended up applying this solution:

beforeRouteLeave(to, from, next) {
    const query = {
        ...to.query,
        utm_campaign: 'from_our_friends'
    };
    if (!to.query.utm_campaign) { // otherwise you'll get 'infinite redirection' error
        next({ path: to.path, query });
    } else {
        next()
    }
}

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28414

You can add a navigation guard to the page component that adds an extra query param to the next destination:

beforeRouteLeave(to, from, next) {
  const query = { ...to.query, utm_campaign: "from_our_friends" };
  next({ query });
}

Upvotes: 1

Related Questions