vue在hash路由模式下实现点击定位滑动

背景:一般是使用锚点来实现dom的定位,但在hash模式下,这种方式不行,会刷新路由,没法实现dom定位的效果。

其实scrollIntoView就可以解决这个问题,scrollIntoView可以将调用它的元素滚动到浏览器窗口的可见区域。

代码实现:

css 复制代码
<!--html模块-->
<div class="bottom-wrapper">
        <div class="left">
            <div @click="goToDom(item.value)" v-for="(item,index) in menuList" :key="index" class="menu-item">
                <span>{{item.name}}</span>
            </div>
        </div>
        <div class="right">
            <div class="scroll-container">
                <div class="scroll-page" ref="modelA">
                    <div class="head">模块1</div>
                 </div>
                <div class="scroll-page" ref="modelB">
                    <div class="head">模块2</div>
                 </div>
                <div class="scroll-page" ref="modelC">
                    <div class="head">模块3</div>
                 </div>
            </div>
</div>
css 复制代码
//关键方法
//跳转到指点的位置
 const goToDom = (refName) => {
        proxy.$refs[refName].scrollIntoView({block: 'start', behavior: 'smooth'});
  }
css 复制代码
    .bottom-wrapper {
        display: flex;
        margin: 10px;
        scroll-behavior: smooth;
        height: calc(100% - 365px);

        .left {
            width: 150px;
            @include box-ht;
            display: flex;
            flex-direction: column;
            align-items: center;

            .menu-item {
                margin: 5px 0;
                border-bottom: 1px solid $theme-bg;
                padding-bottom: 5px;
                color: #000000;
                &:hover{
                    cursor: pointer;
                }
            }
        }

        .right {
            margin-left: 10px;
            width: calc(100% - 150px);
            height: 100%;

            .scroll-container {
                /* 核心代码:缓慢滚动过渡 */
                scroll-behavior: smooth;
                display: block;
                height: 100%;
                overflow-y: scroll;
            }

            .scroll-page {
                position: relative;
                @include box-ht;
                margin: 10px 0;

                .head {
                    font-weight: bold;
                    border-bottom: 1px solid $theme-bg;
                    padding-bottom: 5px;
                }
            }
        }
    }
相关推荐
幼儿园技术家16 分钟前
为什么 SSR 一定会有 hydration mismatch?
前端
FlyWIHTSKY17 分钟前
Vue 3 中 RouteRecord 详解(Vue Router 4)
前端·javascript·vue.js
yingyima29 分钟前
用 cron 定时发送邮件报告:实战案例详解
前端
GAMC35 分钟前
从 “凭感觉写代码” 到 “按规范做开发”:OpenSpec 让 AI 编程回归工程化
前端·人工智能
微学AI1 小时前
Claude-Code-python 前端改造项目工作流程详解
开发语言·前端·python
清汤饺子1 小时前
【译】我的 AI 进阶之路:从怀疑到深度整合
前端·javascript·后端
@菜菜_达1 小时前
Vue生命周期
前端·javascript·vue.js
每天吃饭的羊1 小时前
UMD和IIfe
开发语言·前端·javascript
前端那点事2 小时前
Vue线上代码调试全攻略(安全无侵入,新手也能上手)
前端·vue.js
前端那点事2 小时前
Vue批量文件上传并发踩坑指南:3步解决阻塞、限流、进度混乱
前端·面试