vue2导航栏鼠标放上去有个横杆
时间: 2023-11-01 21:54:20 浏览: 51
要实现鼠标放上去下划线的效果,可以使用Vue的事件绑定和样式绑定。
首先,在`data`中添加一个`hoverIndex`属性,用于记录鼠标悬浮时的索引值:
```
data() {
return {
// ...
hoverIndex: -1,
// ...
}
},
```
然后,在模板中的`li`标签上添加`@mouseover`和`@mouseleave`事件绑定,并且使用三元表达式来动态绑定`tab-current`类名:
```
<li v-for="(item, index) in tabList" :key="index" class="tab"
:class="{'tab-current': index == currentIndex || index == hoverIndex}"
@click="clickTab(index)"
@mouseover="hoverIndex = index"
@mouseleave="hoverIndex = -1">
{{ item }}
</li>
```
最后,需要修改`clickTab`方法和`slideLineLeft`方法,使下划线的位置也能根据`hoverIndex`进行动态变化:
```
clickTab(index) {
this.currentIndex = index
this.slideLeft = this.calculateSlideLeft(index)
},
slideLineLeft() {
this.tabLen = this.tabList.length
this.slideLeft = this.calculateSlideLeft(this.currentIndex)
},
calculateSlideLeft(index) {
const left = this.width / this.tabLen / 2
return left * (index * 2 + 1) + '%'
}
```
这样,当鼠标放上去时,下划线的位置会根据`hoverIndex`的值动态变化。