More articles

preface

I’ve shared composite apis many times before, and today I’m going to share some of the things that came out of it, starting with a simple useTimeout

origin

SetTimeout everyone must be familiar with, but in the process of using it is rarely done to clear the timer operation when the component is unloaded, for a variety of reasons, chase travel here to do a simple package of setTimeout, we also incidentally understand the combined API to bring the silky experience

introduce

UseTimeout is an encapsulation of setTimeout. The main optimization is to clear the timer when components are uninstalled

use


import useTimeout from '@/hooks/useTimeout'

const { perTimeout } = useTimeout()

perTimeout(() = > console.log('test'), 1000)
Copy the code

The ginseng

parameter instructions type An optional value The default value
perTimeout The optimized setTimeout Function(callback, time)

PerTimeout Params

parameter instructions type An optional value The default value
callback The callback function Function
time Delay time Number 0

The source code

The source code is very simple, here directly posted

import { ref, onUnmounted } from '@vue/composition-api'

/** * Scenarios: this applies to setTimeout. SetTimeout * is cleared when the component is uninstalled after use@param Callback executes the main function *@param Time time * /

export default() = > {const timer = ref(null)
  const perTimeout = (callback = null, time = 0) = > {
    timer.value = setTimeout(() = > {
      callback && callback()
    }, time)
    return timer.value
  }
  // The component uninstallation is cleared
  onUnmounted(() = > {
    if (timer.value) {
      clearTimeout(timer.value)
      timer.value = null}})return {
    perTimeout
  }
}

Copy the code

conclusion

Using useTimeout as an introduction, we open the wrapper for our series of composite apis

extension

Recently watch “Heaven” TV series, feel a lot, some views and the men and women happen to agree:

  • The traditional concept of the dead knot in a “rely” on the word, rely on parents at home, go out to rely on friends, rely on God, rely on bodhisattva, rely on the emperor grace…… In short, by anything, is not on their own, so can only kneel in the spirit

  • If my worth can only make me poor, then poor is my worth