v-throttle
介绍
v-throttle
指令用于给按钮添加节流功能。它可以限制用户在一定时间内重复点击按钮的次数,特别适用于频繁触发的事件处理场景,如搜索按钮、提交按钮等。
使用方法
在按钮上使用 v-throttle
指令,并将事件处理函数作为指令的值传入:
点击次数:0
查看代码
vue
<template>
<div class="container">
<a-button v-throttle="handleClick" shape="round" long size="large" type="primary">点击按钮</a-button>
<div class="result">点击次数:{{ clickCount }}</div>
</div>
</template>
<script setup>
import { vThrottle } from '@cp-vuedir/core'
import { ref } from 'vue'
const clickCount = ref(0)
const handleClick = () => {
clickCount.value++
}
</script>
<style scoped>
.throttle-demo {
display: flex;
flex-direction: column;
gap: 2rem;
}
.demo-button {
padding: 8px 16px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 8px 0;
}
.demo-button:hover {
background-color: #45a049;
}
.result {
margin-top: 8px;
color: var(--vp-c-text-1);
font-size: 0.9em;
}
h3 {
margin: 0 0 1rem 0;
color: #333;
}
</style>
API
属性名 | 说明 | 类型 | 是否必选 | 默认值 |
---|---|---|---|---|
event | 节流触发的回调函数 | Function | - |
注意事项
注意
v-throttle
指令只能用于按钮元素。- 节流延迟时间固定为 300ms,不支持自定义。
- 指令可以不传参数直接使用,也可以传入一个回调函数作为参数。