学习记录:vue3实现平滑跟踪菜单

137 阅读1分钟

平滑菜单的实现

在学习写练习项目的时候遇见了平滑滑动跟随的效果,记录一下自己实现的方法,和知识点的学习,第一次记录还有很多不足,大佬勿喷!!!

1、效果图

屏幕截图 2025-01-06 102522.png

2、点击每一个项进行一个滑动跟踪

首先我们先准备好基本的代码结构和样式

        <div class="files">
                <div class="file-title">文档</div>
                <div class="nav-file" ref="navFile">
                    <div :class="['nav-item']" v-for="(item, index) in menu" :key="item.index"
                        @click="changeIndex(item.index)">{{ item.name }}
                    </div>
                    <span class="active" :style="indicatorStyle"></span>
                </div>
            </div>

css样式代码

 .files {
            margin-top: 20px;

            .file-title {
                font-size: 18px;
            }

            .nav-file {
                margin-top: 18px;
                width: 280px;
                height: 36px;
                background-color: #eee;
                border-radius: 8px;
                display: flex;
                align-items: center;
                position: relative;


                .nav-item {
                    cursor: pointer;
                    padding: 2px 16px;
                    margin-left: 6px;
                    border-radius: 6px;
                    z-index: 10;
                    text-align: center;
                }

                .active {
                    text-align: center;
                    background-color: #fff;
                    padding: 2px 16px;
                    border-radius: 6px;
                    position: absolute;
                    height: 30px;
                    bottom: 0;
                    left: 0;
                    top: 3px;
                    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                }
            }
        }

也可以根据自己喜欢的样式来进行修改

nav-file我们在类上面绑定了一个ref,通过ref配合js来实现效果,还创建了一个sapn作为块来进行一个移动,查看js代码

// 滑动菜单
const menu = ref([
    { index: 0, name: '编辑过' },
    { index: 1, name: '浏览过' },
    { index: 2, name: '收藏的' }
])

let selectIndex = ref(0)
const changeIndex = (index) => {
    selectIndex.value = index
}
// 滑动指示器功能
const navFile = ref()
const indicatorStyle = computed(() => {
    if (!navFile.value) return {};
    const target = navFile.value.querySelector(`.nav-item:nth-child(${selectIndex.value + 1})`);
    if (!target) return {};
    return {
        transform: `translateX(${target.offsetLeft}px)`,
        width: `${target.offsetWidth}px`,
    };
});

通过计算属性来实现动态计算移动的值

这样我们就可以实现一个平滑跟踪的效果了