Vue中如何自定义(v-throttle)节流指令

背景:在开发中,我们经常会在搜索框中使用防抖或节流进行优化,因此为了方便,今天我们自定义一个(v-throttle)指令。

自定义指令语法:可参考官方文档

1.在项目的utils目录下定义util.js模块(通常该模块放一些通用的工具方法):

export const throttle = (callback, delay) => {
  let timer = null
  return (e) => {
    if (!timer) {
      timer = setTimeout(() => {
        callback(e)
        timer = null
      }, delay)
    }
  }
}

2.在项目的directive目录下定义throttle.js模块(定义指令):

import { throttle } from '@/utils/util'
export default {
  install(Vue, options = {}) {
    Vue.directive('throttle', {
      bind(el, binding) {
        let execFunc
        // 当绑定的函数带有参数,则binding.value是一个数组
        if (binding.value instanceof Array) {
          const [func, time = 500] = binding.value
          execFunc = throttle(func, time)
        } else {
          // 当仅仅绑定一个函数名,则binding.value就是一个函数名
          execFunc = throttle(binding.value, 500)
        }
        el.addEventListener('click', execFunc)
      },
    })
  },
}

3.在项目的main.js中注册v-throttle指令:

import Vue from 'vue'
import Throttle from '@/utils/util'
Throttle.install()

4.在组件中使用:

<template>
  <div class="container">
    <input type="text"
           v-model="queryString"
           v-throttle="searchContent">
  </div>
</template>

<script>
import { remoteSearch } from '@/api/xxxx'
export default {
  name: 'test',
  data () {
    return {
      queryString: ''
    }
  },
  methods: {
    async searchContent () {
      var data = {
        keyword: this.queryString
      }
      var res = await remoteSearch(data)
      if (res.code === 0) {
        //...
      }
    }
  }
}
</script>

<style>
</style>

5.最后:实现一个自定义的指令并不难,根据场景选择合适的钩子函数进行相应的逻辑实现即可。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值