VUE+Typescript(TSX)使用函数防抖、函数节流

6 篇文章 0 订阅
1 篇文章 0 订阅
1、在utils文件夹下创建tool.ts工具类文件
/**
 * 函数防抖: 在一定时间内,在动作被连续频繁触发的情况下,动作只会被执行一次
 * @param fn 回调函数
 * @param wait 等待时间
 */
export function debounceFun(fn, wait = 600) {
    // 手动指定一个类型,any 可以被断言为任何类型
    let _this = this as any
    // 接收参数 对象
    let args = arguments
    return function () {
        if (_this.timeout) {
            // 清除定时器
            clearTimeout(_this.timeout)
        }
        // 添加定时器
        _this.timeout = setTimeout(() => {
            fn.apply(_this, args)
        }, wait)
    }
}

/**
 * 函数节流: 在指一定时间内执行的操作只执行一次
 * @param fn 回调函数
 * @param wait 等待时间
 */
export function throttleFun(func,delay = 600){
    // 手动指定一个类型,any 可以被断言为任何类型
    let _this = this as any
    // 接收参数 对象
    let args = arguments
    return function(){
        if (_this.timeout) {
            return
        }
        // 添加定时器
        _this.timeout = setTimeout(() => {
            func.apply(_this, args)
            _this.timeout = null
        },delay)
    }
}


<template>
  <div class="box">
  	<!-- 使用的Vue-ant-design-vue前端框架 -->
    <a-input
        v-model="userName"
        @change="changeValue()"
    />
  </div>
</template>
<script lang="tsx">
import Component from 'vue-class-component'
import { Vue } from 'vue-property-decorator'
// 引入函数防抖
import { debounceFun } from "@/utils/tool"

@Component({
    components: {}
})
export default class Main extends Vue {
    userName: string = ''
    // input 内容发生改变则触发
    changeValue(){
    	//调用
		debounceFun.bind(this)(() => {
			console.log(this.userName)
		}, 1000)()
	}
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值