目录
1. 实现说明:
在切换导航栏时,高亮显示当前所选中的导航栏
如果选择的不是当前所选择的导航栏,有滑动的效果
2. 基础代码讲解
首先定义导航栏上的元素,这里以两个元素的导航栏为例,一共有两个元素,分别是默认和最新
最下面的是实现滑动效果
<view class="nav-list">
<text :class="{'nav': true, 'active': currentNavIndex === 0}" @click="toggleNav(0)">默认</text>
<text :class="{'nav': true, 'active': currentNavIndex === 1}" @click="toggleNav(1)">最新</text>
<text :class="{'move-animation':true,'moveLeft':moveNavAnimation === 0,'moveRight':moveNavAnimation === 1}"></text>
</view>
3. :class写法简介
在 Vue.js 中,:class 是一个绑定表达式,用于动态地切换元素的类。以上面的最后一个滑动效果实现的:class为例讲解,以下是对 :class="{'move-animation':true,'moveLeft':moveNavAnimation === 0,'moveRight':moveNavAnimation === 1}" 写法的说明:
- {'move-animation':true}:这部分表示 move-animation 类将被始终添加到元素上,因为条件是 true。无论什么情况下,这个类都会被应用。
- {'moveLeft':moveNavAnimation === 0}:这部分是一个条件类绑定。它表示如果 moveNavAnimation 的值等于 0,则 moveLeft 类会被添加到元素上。如果 moveNavAnimation 不等于 0,则 moveLeft 类不会被添加。
- {'moveRight':moveNavAnimation === 1}:这部分也是条件类绑定。它表示如果 moveNavAnimation 的值等于 1,则 moveRight 类会被添加到元素上。如果 moveNavAnimation 不等于 1,则 moveRight 类不会被添加。
4. 切换导航栏所调用的变量和函数
这里主要是标记:当前所选择的导航栏以及要调用的滑动效果
const currentNavIndex = ref(0)
const moveNavAnimation = ref(0)
const toggleNav = (index) => {
currentNavIndex.value = index
moveNavAnimation.value = index
}
5. 实现效果的样式
.nav-list{
font-size: 20rpx;
font-weight: bold;
background-color: #ededed;
border-radius: 23rpx;
width: 224rpx;
height: 60rpx;
display: flex;
justify-content: space-between;
align-items: center;
padding: 2rpx;
position: relative;
}
.nav{
color: #b4b4b4;
width: 110rpx;
height: 56rpx;
border-radius: 23rpx;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
}
.move-animation{
width: 110rpx;
height: 56rpx;
background-color: #ffffff;
transition: 0.6s;
position: absolute;
border-radius: 23rpx;
}
.active{
color: #10050b;
}
.moveLeft{
left: 4rpx;
}
.moveRight{
left: 50%;
}