节流

106 阅读1分钟

第一种节流

export default {
  data() {
    this.demo = this.throttle(this.demo, 1000);
    return {

    }
  },

  methods: {
  //需要节流的函数
    demo() {
      console.log("节流");
    },

    throttle(func, wait) {
      let timeout = null
      return function () {
        const context = this
        const args = arguments
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = null
            func.apply(context, args)
          }, wait)
        }
      }
    }


  },

}

第二种节流 _.throttle _.debounce(这是防抖换个函数名即可)

//引入node_modules自带的lodash (这是全部的lodash函数)
import _ from 'lodash'



//按需引入 查看node_modules里面的lodash文件里面的文件或者lodash官网查看
import throttle from 'lodash/throttle'



  methods: {
  //要节流的方法  () 
    demo: _.throttle(function () {

      console.log("测试节流");
    }, 1000)
    
    
   //按需引入的使用方法 
     demo: throttle(function () {
          console.log("测试节流");
    }, 1000)
    
  },