Vue implements navigation dynamic style switching

The code is as above, simply adding styles dynamically:

But I don’t know why the style is switched like this. It takes two clicks for the style to take effect, and the homepage always has the style automatically

Click on my 1, no style

Click twice for the style to take effect, click twice for list 3

Baidu took a look, the solution (using vue's active-class):

1. The role of active-class

active-class is an attribute in the router-link component of the vue-router module, which is used to switch the selected style;

2. There are two ways to use active-class in vue-router:

a. Configure linkActiveClass directly in the routing js file

export default new Router({
  linkActiveClass: 'active'
})

b. Write active-class in router-link

<router-link to="/home" class="menu-home" active-class="active">首页</router-link>

3. If you use the second method to add active-class, after jumping to my page, the two router-links will always have the selected style, the code is as follows

<div class="menu-btn">
  <router-link to="/" class="menu-home" active-class="active">
    首页
  </router-link>
</div>
<div class="menu-btn">
  <router-link to="/my" class="menu-my" active-class="active">
    我的
  </router-link>
</div>

It may be caused by to="/". When active-class selects a style, it matches according to the path in the route, and then displays it. For example, in my page, the route is localhost:8080/#/my, then to="/" Both to="/my" can be matched, and all will activate the selected style

4. There are two ways to solve the problem, both by adding an exact attribute

a. Configure linkActiveClass directly in the routing js file

export default new Router({
  linkExactActiveClass: 'active',
})

b. Write exact in router-link

<router-link to="/" class="menu-home" active-class="active" exact>首页</router-link>

5. It can also be solved in this way

<router-link to="/home" class="menu-home" active-class="active" exact>首页</router-link>
路由中加入重定向
{
  path: '/',
  redirect: '/home'
}

Guess you like

Origin blog.csdn.net/weixin_47190898/article/details/128177211