The React community has embraced Hook. Vue3 release also supports custom Hook, as Vue only front-end small code farmers naturally want to see what Vue3 Hook is exactly black magic?

Of the personal blog website welcome communication: firefly: https://blog.xkongkeji.com

React Hook What is a Hook?

  • Vue official customizationHookHere’s an example:
import { ref, onMounted, onUnmounted } from "vue";

export function useMousePosition() {
  const x = ref(0);
  const y = ref(0);

  function update(e) {
    x.value = e.pageX;
    y.value = e.pageY;
  }

  onMounted(() => {
    window.addEventListener("mousemove", update);
  });

  onUnmounted(() => {
    window.removeEventListener("mousemove", update);
  });

  return { x, y };
}
Copy the code

Components used in:

import { useMousePosition } from "./mouse"; export default { setup() { const { x, y } = useMousePosition(); return { x, y }; }};Copy the code

I believe that those who wrote VUe2 should have been dominated by mixins, especially when they got the project they were not familiar with. It was a nightmare. All kinds of mixins, variables and methods could not be seen where they came from.

Y is derived from useMousePosition function. UseMousePosition is a function that uses composition-API to define responsive data X and Y and then exports it. Personally, I feel that MIXin has been split. The operation of import was handed over to the developers. Previously, VUE directly helped us merge the data together, which led to the problem that the data could not be traced.

Personally understand, welcome to correct

  • hookCan be regarded as a formermixinTo use
  • hookPhi is a function,mixinIt’s an object
  • hookIt’s a split versionmixin, hand over the import operation to the developer,mixinStudent: According to the correspondingoptions ApiMerge directly into components
  • hookYou can borrowcomposition-apiFully using thevueAbility, in short, is what you aresetupThe delta function workshookAll can use.

reference

1. [Intensive reading of Vue3.0 Function API] juejin.cn/post/684490…

2, [Vue3 what fortunately? (detailed contrast and React hooks)]] segmentfault.com/a/119000002…