Using good hook methods in Vue development can make your code more modular and maintainable

Callback Function:

A callback function is a mechanism for passing functions as arguments to other functions. When a specific operation or event is completed, the callback function will be called and the corresponding code logic will be executed. Callback functions are commonly used in asynchronous programming and event-driven programming models.

var a = 0
 
function bb(x) {
    console.log(x)
}
 
function timer(time, callback) {
    setTimeout(function () {
        a = 6
        callback(a);
    }, time);
}
 
//调用:
console.log(a)
timer(3000,bb)
hook method

The hook method is a type of callback function. Hook method is a software design pattern in which a class defines a template method in which part of the code is fixed and another part of the code can be customized by subclasses by implementing the hook method. This also allows for better abstraction: abstractly exposing frequently changing content and encapsulating fixed code.

Each life cycle of Vue is actually some hooks specified by Vue developers, which are similar to the hooks specified in git. You only need to fill in custom content into the hook, and it can be executed. For example, beforeCreate, created, mounted, etc. in the vue instance are all hooks.

Example 1 (Use and destruction of timer)
  • This is how we generally operate:

1. The vue instance needs to have an instance of this timer, which feels a bit redundant.
2. The code for creating the timer and the code for destroying the timer are not put together. It is usually easy to forget to clean up the timer and it is not easy to maintain;

<script>
  export default {
  	data() {
  		return {
			timer: null
		}
  	},
    mounted() {
      this.timer = setInterval(() => { ... }, 1000)
    },
    beforeDestroy() {
      clearInterval(this.timer)
      this.timer = null
    }
  }
</script>
  • In fact, a better approach is this:

Use hooks to monitor the beforeDestory life cycle. Because it is enough to monitor once, use $once to register the monitor.

<script>
  export default {
    mounted() {
      const timer = setInterval(() => { ... }, 1000)
      this.$once('hook:beforeDestroy', () => clearInterval(timer))
    }
  };
</script>
Example 2 (Listening to component life cycle)

Adding a listener to mounted requires removing the listener in beforeDisroy. Considering some reasons, you don't want to write a beforeDisroy to implement it. At this time, we can use hook.

mounted () {
  window.addEventListener('online', this.handleOnline)
  this.$once('hook:beforeDestroy', function () {
    window.removeEventListener('online', this.handleOnline)
  })
},

Although they work similarly, $emit, $on, and $off are not aliases for dispatchEvent, addEventListener, and removeEventListener.

Example 3 (parent component listens to the life cycle of child components)

How does the parent component do certain processing in the mounted life cycle of the child component?
Is your first thought to emit the parent component during the mounted cycle of the child component?

  • Ordinary writing
// 父组件中这样写
<child-component @childMounted="handleChildMounted"></child-component>
// 子组件中这样写
mounted () {
  this.$emit('childMounted')
},
  • Better way to write
// 父组件中这样写
<child-component @hook:mounted="handleChildMounted"></child-component>
// 子组件中不用写东西
mounted () {},

Use @hook directly in the parent component to listen to the hook function in the child component, without $emit once in the child component. Of course, we can also listen to other hook functions in Vue, such as @hook:created, @hook:destroyed, etc.

Example 4 (Listening to the life cycle of third-party components)

You are using a third-party component library. You need to do some operations when the component is rendered or changed. Fortunately, this component has not implemented the corresponding callback. What should you do? You can use hooks at this time!

<el-calendar 
@hook:mounted="calendarRender"
@hook:updated="calendarUpdated"
>
</el-calendar>
Dynamic instruction usage

$on
Use: vm.$on(‘event name’,callback)
Description: Listen to custom events on the current instance. Events can be triggered by vm.$emit. The callback function receives any additional parameters passed into the event triggering function.

$once
Use: vm.$once('event name',callback)
Description: Listen to a custom event, but only trigger it once. Once triggered, the listener will be removed.

$off
Use: vm.$off('event name',callback)
Description: Remove custom event listener a>

$emit
Use: vm.$emit('event name',args)
Description: The way the child component passes communication to the parent component

Guess you like

Origin blog.csdn.net/shanghai597/article/details/130868733