实现原理
点击后只要获取到当前点击项的前一个和后一个添加类名,去改变样式
实现步骤
1.循环菜单,并设置动态class类名【关键】
<div class="menu">
<div
v-for="(item, index) in menuItems"
:key="index"
:class="[
'menu-item',
{ active: activeIndex === index },
{ next: activeIndex === index - 1 },
{ previous: activeIndex === index + 1 },
]"
@click="setActive(index)"
>
{{ item }}
</div>
</div>
2.创建变量和方法
// 菜单名称
const menuItems = ref(['选项一', '选项二', '选项三', '选项四']);
// 当前选中的项
const activeIndex = ref(null);
// 通过点击事件改变选中的项
const setActive = index => {
activeIndex.value = index;
};
3.css样式
<style scoped>
.menu {
width: 200px;
border-radius: 8px;
overflow: hidden; /* 防止子元素圆角溢出 */
}
.menu-item {
padding: 30px;
cursor: pointer;
background-color: #f0f0f0;
transition: background-color 0.3s ease;
}
.menu-item:last-child {
border-bottom: none;
}
/* 选中项 */
.menu-item.active {
background-color: #fff;
}
/* 选中项 的 下一个菜单 */
.menu-item.next {
background-color: pink;
border-top-right-radius: 20px;
}
/* 选中项 的 上一个菜单 */
.menu-item.previous {
background-color: yellow;
border-bottom-right-radius: 20px;
}
</style>