vue-router4 (七) 滚动行为(scrollBehavior )

应用场景:

从A组件进入B组件,再返回A组件后,想让A组件的页面回到进入B组件前的位置,或者自动刷新回到A组件顶部,就需配置路由的滚动行为(scrollBehavior )。

①返回A组件时,让A组件回到进入B组件前的位置,路由配置:

复制代码
const router = createRouter({
    history:createWebHistory(),  //路由模式
    routes,   //路由配置项
    //滚动行为
    scrollBehavior (to, from, savedPosition) {
        //console.log(savedPosition);
        if (savedPosition) {
            return savedPosition
        } else {
            return{
                top:0,
                left:0
            }
        }
    }
 })

②返回A组件时,让A组件自动刷新回到顶部:

复制代码
 scrollBehavior (to, from, savedPosition) {
      return{
          top:0,
          left:0
      }
}
相关推荐
NiceCloud喜云7 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby7 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩7 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
Front思8 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫10 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。11 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星11 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒11 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端
丷丩12 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
Mr.Daozhi12 小时前
RAG 进阶实战:跑通 Demo 后我连续翻了 6 次车,逐一修复才真正可用(含 Gradio Web 版)
前端·数据库·langchain·大模型·gradio·rag·科研工具