Skip to content

Throttle 示例

对事件处理函数进行节流,限制执行频率。

节流按钮

vue
<template>
  <div>
    <button v-throttle:1s="increment" class="btn">
      点击我 (1秒节流)
    </button>
    <p>点击次数: {{ count }}</p>
    <p class="hint">每秒最多只能点击一次</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)

function increment() {
  count.value++
}
</script>

<style scoped>
.btn {
  padding: 12px 24px;
  background: #42b883;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.btn:hover {
  background: #3aa876;
}

.hint {
  color: #666;
  font-size: 14px;
}
</style>

滚动进度

vue
<template>
  <div class="container">
    <div class="progress-bar" :style="{ width: progress + '%' }"></div>
    <p>滚动进度: {{ progress }}%</p>

    <div class="scroll-area">
      <p v-for="i in 20" :key="i">
        向下滚动查看进度条更新 (100ms 节流)
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const progress = ref(0)

function handleScroll(event) {
  const { scrollTop, scrollHeight, clientHeight } = event.target
  const maxScroll = scrollHeight - clientHeight
  progress.value = Math.round((scrollTop / maxScroll) * 100)
}

onMounted(() => {
  const scrollArea = document.querySelector('.scroll-area')
  if (scrollArea) {
    scrollArea.addEventListener('scroll', handleScroll)
  }
})
</script>

<style scoped>
.container {
  position: relative;
}

.progress-bar {
  height: 4px;
  background: #42b883;
  transition: width 0.1s;
}

.scroll-area {
  height: 200px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 16px;
  margin-top: 16px;
}
</style>

鼠标位置追踪

vue
<template>
  <div
    v-throttle:50ms="handleMouseMove"
    class="tracking-area"
    @mousemove="handleMouseMove"
  >
    <p>在此移动鼠标</p>
    <p>位置: {{ x }}, {{ y }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const x = ref(0)
const y = ref(0)

function handleMouseMove(event) {
  x.value = event.clientX
  y.value = event.clientY
}
</script>

<style scoped>
.tracking-area {
  width: 100%;
  height: 200px;
  background: #f5f5f5;
  border: 2px dashed #ddd;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  user-select: none;
}
</style>

在线体验

Open in StackBlitz

基于 MIT 许可发布