SoFunction
Updated on 2025-04-04

Example of method for encapsulating throttling functions in Vue custom instruction

Throttle functions are a development technique commonly used in web front-end development. In real-time search of input, scrolling events, etc., in order to avoid excessive performance consumption, we will use throttling functions. There is an example in the book "Advanced Programming of JavaScript":

function throttle (method, context) {
  clearTimeout(())
   = setTimeout(function () {
   (context)
  }, 100)
 }

 function resizeDiv () {
  var div = ('myDiv')
   =  + 'px'
 }

  = function () {
  throttle(resizeDiv)
 }

This is a very typical application of function throttling. Without further explanation, this article encapsulates similar methods through vue's custom instructions.

 <template>
 <div>
  <input
   type="text"
   v-model="text"
   v-debounce="search"
  >
 </div>
</template>
<script>
 export default {
  name: 'debounce',
  data () {
   return {
    msg: 'Welcome to Your  App',
    text: '',
    count: 1
   }
  },
  directives: {
   debounce: {
    inserted: function (el, binding) {
     let timer
     ('keyup', () => {
      if (timer) {
       clearTimeout(timer)
      }
      timer = setTimeout(() => {
       ()
      }, 300)
     })
    }
   }
  },
  methods: {
   search () {
   // The actual operation to be performed ('') or something like    ++
    ('count is:' + )
   }
  }
 }
</script>

The above code implements a real-time search class function throttling, which is implemented through the vue custom instruction v-debounce. Originally, if we wanted to do an implementation search, we would directly use @keyup=search, which would be very performance-consuming. After typing on the keyboard, we would call a search event. If it is an ajax request, it would be very unfriendly. Therefore, through v-debounce, we can organize and run it while the keyboard is continuously typing, and stay for 300 milliseconds before executing.

Through the custom directive of vue, it can also be mounted globally, so that it can be called globally through v-debounce. This is much simpler than traditional methods and does not require call, apply, etc.

Key points: The parameter binding passed by the custom directive of vue If it is a function, it is executed through (). Through the above example, you can also pass events, binding objects, etc. The above example binds to el and keyup events. These can also be passed through binding. Through the custom directive of vue, a lot of duplicate code can be simplified and the logic is clearer.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.