项目中遇到了防抖和节流,所以整理一下,并且在3.0中尝试

  1. 防抖:在一段时间内函数只会执行一次,如果在这个时间段内再次触发函数,则重新计算函数执行时间(可以用作提交事件,防止用户重复提交)
<template>
  <div>{{num}}</div>
  <button @click="add">add</button>
</template>
<script>
  import { ref, reactive } from 'vue'
  export default {
    name: 'TestChildren',
    setup () {
      const num = ref(1)
      const add = debounce(()=>{
        num.value++
      }, 2000)
      return {
        num,
        add,
      }
    },
  }
  //防抖
  function debounce (fn, delay) {
    let timer
    return function () {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn()
      }, delay)
    }
  }
  }
  1. 节流:在一段时间内,函数最多可以触发一次执行(滚动加载的时候,当滑动到底部时,一直滑动那么每隔一定时间就会执行一次加载)
<template>
  <div>{{num}}</div>
  <div>{{nums}}</div>
  <button @click="add">add</button>
  <div>{{foo}}</div>
  <div>{{bar}}</div>
  <div>x:{{x}}, y:{{y}}</div>
</template>

<script>
  import { watch, ref, computed, reactive, toRefs, onMounted, onUnmounted } from 'vue'
  import useMouse from '../utils/listenMouse'

  export default {
    name: 'TestChildren',
    props: {
      childCount: Number
    },
    setup (props) {
      const num = ref(1)
      // let nums = computed(() => num.value + 1)
      let nums = ref(0)
      let { x, y } = useMouse()
      const add = debounce(()=>{
        num.value++
      }, 2000)
      watch(num, () => {
        nums.value += 3
      })
      const { foo, bar } = useFeatureX()
      onMounted(()=>{
        document.addEventListener('scroll', throttle(()=>{
          console.log('节流')
        },200), true)
      })
      onUnmounted(()=>{
        document.removeEventListener('scroll',throttle(), true)
      })
      return {
        num,
        nums,
        add,
        foo,
        bar,
        x,
        y
      }
    },
  }

  function useFeatureX () {
    const states = reactive({
      foo: 1,
      bar: 2
    })
    return toRefs(states)
  }

  //防抖
  function debounce (fn, delay) {
    let timer
    return function () {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        fn()
      }, delay)
    }
  }

  //节流
  function throttle (fn, delay) {
    let isThtottle = ref(true)
    return () => {
      if (!isThtottle.value) return
      isThtottle.value = false
      setTimeout(() => {
        fn()
        isThtottle.value = true
      }, delay)
    }
  }
</script>

<style scoped>

</style>

Logo

前往低代码交流专区

更多推荐