SoFunction
Updated on 2025-04-05

Example of using global routing hooks to add common parameters to url in vue

Sometimes we may have such a requirement, for example, now the url is /#/ We need to monitor whether there is a parameter abc whenever the user jumps to the route. If so, the backend requires us to carry this parameter in the url when jumping any url in the future. This becomes /#/&abc=xxx;

This parameter is called "common parameter";

So, how should we do it? Because there are many components in vue. If you write each component, it is too troublesome. So at this time, the global routing hook appears. The following are

Global navigation front guard Execute before routing jump

Newly added to global navigation analysis guard vue2.5. Before navigation is confirmed, after all components are guarded and asynchronous routing components are parsed, the parsing guard is called.

Global navigation rear guard execution after routing jump

We used the front guard this time. At first I used the rear guard. Because of a bug, it may be that my skills are not good. Later, I changed to the front guard.

The code is as follows:

((to, from, next) => {
 if () {
  next();
  return;
 };
 if () {
  let toQuery = (());
   = ;
  next({
   path: ,
   query: toQuery
  })
 } else {
  next()
 }
 
 });

Here is an explanation: The front guard must remember to execute the next method. If it is not executed, the route will not jump. When the route is redirected, if we output from and to. They represent the previous route and the current route respectively. If we want to adjust from a to b; that is, when redirecting, we immediately obtain the route address of b. And determine whether the route b has the a parameter. If there is, jump directly, and the next method is executed. And return; if there is no, then if the url of a has the a parameter, then we put this parameter on the url of b; and the next method is executed. Just carry this parameter. Finally, if a does not have this parameter, execute the next method directly. That is to say, the route jumps directly and does not intercept any.

Another thing to remind beginners is that beginners are prone to encountering dead loops when they just use routing hooks. It is recommended to take a good look at the execution mechanism of routing hooks. You will not encounter dead loops. If you have time, let me talk about this problem.

The above example of using global routing hooks to add public parameters to the url in vue is all the content I share with you. I hope you can give you a reference and I hope you can support me more.