1

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.

4
  • Can you provide some more context around the why? If for instance it's because you want to track every pageview for the session that originated with that campaign, there are other ways Commented Nov 3, 2021 at 20:07
  • @Ohgodwhy , yes, I'm trying to know where to users go from one certain page with utm args. And that page uses common components that have router links Commented Nov 3, 2021 at 20:10
  • 1
    So to be clear it's the links going out from the landing page you wish to track as opposed to the entire navigation experience? Commented Nov 3, 2021 at 20:15
  • @Ohgodwhy exacty. In other words, I want to pass default query to all possible router-links on a certain page. Commented Nov 3, 2021 at 20:19

2 Answers 2

1

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 });
}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this and it WORKS. I was almost sure that I should use beforeRouteLeave or beforeRouteUpdate, but I couldn't find a way to make it work as needed. Thanks a lot.
I've discovered another problem. With next({ query }) it adds args to the URL, but doesn't change the path to the page. If I use next({ path: to.path, query}), then I get infinite redirection error. Do you have any idea how to fix this @Majed Badawi ?
Never mind. I found the solution. I'll update my question adding the fix.
0

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()
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.