Vue-Router 第十三节:滚动行为

65 阅读1分钟

Vue-Router 第十三节:滚动行为

在使用前端路由时,当我们切换新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。我们就可以使用vue-router ,它让你可以自定义路由切换时页面如何滚动。

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    //  return  ***期望滚动到哪个的位置
  }
})

scrollBehavior 方法接收三个参数: tofrom、第三个参数 savedPosition 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用。

该函数可以返回一个ScrollToOptions 位置对象: { top: 100, left: 100}

const router = createRouter({
    history: createWebHashHistory(),
    routes: [...],
    scrollBehavior(to, from, savedPosition) {
        // return 期望滚动到哪个的位置
        return {
            top: 100,
            left: 100,
            behavior: "smooth"  // 定义滚动行为
        }
    }
})
​

来个的案例吧~

// router/index.ts
import About from '@/views/about/index.vue'
import path from 'path';
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
// 1、定义路由 每个路由都需要映射到一个组件。
const routes: Array<RouteRecordRaw> = [
    // 可直接导入或者引入
    {
        path: '/',
        component: () => import("@/views/login/index.vue")
    },
    {
        path: '/home',
        component: () => import("@/views/home/index.vue")
    }
]
​
// 2、创建路由实例并传递routes
const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { top: 1000 }   // ******* 设置滚动到哪个的位置
    }
})
​
// 导出
export default router
​
// home/index.vue (这么粗暴的写法请勿学习哈哈哈)
<template>
    <div style="height: 2000px; background-color: aquamarine;">
        <H1>
            我是Home页面
        </H1>
        <h2 style="margin-top: 900px; height: 10%; background-color: brown;">
            我是Home页面
        </h2>
    </div>
</template>
​
<script setup lang="ts">
​
</script>
​
<style></style>

1715758121622.jpg