You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何控制VueRouter的平滑滚动速度?

How to Control Vue Router's Smooth Scroll Speed

Great question! The native behavior: 'smooth' option in Vue Router's scrollBehavior doesn't let you adjust scroll speed directly—it relies on the browser's built-in smooth scrolling, which has fixed, unconfigurable timing. But we can work around this by replacing the native smooth scroll with a custom implementation that lets us control the speed exactly.

Here's how to do it:

1. Create a Custom Smooth Scroll Function

First, we'll build a reusable smooth scroll function that takes a target element and a duration (in milliseconds) to define scroll speed. This uses requestAnimationFrame to animate the scroll incrementally for a natural feel.

2. Update Your router.js File

Modify the scrollBehavior method to call this custom function instead of relying on native behavior. We'll return false to tell Vue Router not to handle scrolling natively.

Here's the full updated code:

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../vue/home";
import About from "../vue/about";

Vue.use(VueRouter);

// Custom smooth scroll function with controllable speed
function smoothScrollTo(target, duration = 500) {
  const targetTop = target.getBoundingClientRect().top;
  const startScroll = window.pageYOffset || document.documentElement.scrollTop;
  const targetPosition = startScroll + targetTop;
  const distance = targetPosition - startScroll;
  let startTime = null;

  // Ease-in-out timing for natural scroll motion
  function animateScroll(currentTime) {
    if (startTime === null) startTime = currentTime;
    const timeElapsed = currentTime - startTime;
    const progress = Math.min(timeElapsed / duration, 1);
    const easeProgress = progress < 0.5 
      ? 2 * progress * progress 
      : 1 - Math.pow(-2 * progress + 2, 2) / 2;
    
    window.scrollTo(0, startScroll + (distance * easeProgress));
    
    if (timeElapsed < duration) {
      requestAnimationFrame(animateScroll);
    }
  }

  requestAnimationFrame(animateScroll);
}

export default new VueRouter ({
    mode: "history",
    routes: [
        {path: "/", name: "home", component: Home},
        {path: "/about", name: "about", component: About},
    ],
    scrollBehavior(to, from, savedPosition) {
        // Handle browser back button saved position first
        if (savedPosition) {
          return savedPosition;
        }

        // Use custom scroll for hash targets
        if (to.hash) {
          const targetElement = document.querySelector(to.hash);
          if (targetElement) {
            // Adjust the duration here to change speed: lower = faster, higher = slower
            smoothScrollTo(targetElement, 300);
            // Prevent native scroll behavior
            return false;
          }
        }

        // Default to scrolling to top if no hash or target not found
        return { x: 0, y: 0 };
    }
});

3. Tweak the Scroll Speed

Just modify the duration value in smoothScrollTo(targetElement, 300):

  • 300 = faster scroll (closer to v-smooth-scroll's speed)
  • 800 = slower scroll
  • Adjust to your preferred speed!

How This Works

  • The function calculates the exact distance between your current scroll position and the target element.
  • It uses requestAnimationFrame to update the scroll position in tiny increments over your specified duration.
  • The ease-in-out timing ensures the scroll starts slow, speeds up, then slows down at the end—matching the natural feel of native smooth scrolling, but with full speed control.

内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:58:10