“This is the 20th day of my participation in the First Challenge 2022. For details: First Challenge 2022”


This article is mainly translated from: what-rex-mean-for-vue

By Sarah Drasner

OS: Although this is an April 19 article, it is clear from Hooks, which were corrected by University of Utah. It is a good read to learn about the design and development of Vue Hooks.


The Hooks discussed in this article are different from Lifecycle Hooks, which were introduced in V16.7.0-alpha; Although Hooks are introduced by React, they are essentially important code composition mechanisms that benefit the entire JavaScript framework; Take a moment today to talk specifically about: What do Hooks mean to Vue?

Hooks provide a more explicit way to organize code, make it reusable, and more importantly, allow different parts of logic to communicate and work together.

The problem background

Why are Hooks proposed? As far as React goes, here’s the background to the original problem:

Classes are the most common form of organization when expressing state concepts. The class itself has some problems. For example, the binding relationship is long and complex, making it hard to read. The direction of This is always confusing.

Not only that, in terms of reuse, it is common to use a rendering tool or higher-order component class pattern, but it is easy to fall into a “pyramid of doom” that can be interpreted as excessive nesting;

Hooks are there to solve those problems; Hooks allow us to define component state logic using function calls that are more combinable and reusable. At the same time, state access and maintenance can still be carried out;

Example: @dan_abramov’s code from #ReactConf2018

  • Figure 1.

  • Figure 2.

There is a transformation from figure ① to Figure ②, which combines the component code again and then exports it in a functional way for external reuse.

On the maintenance side, Hooks provide a single, functional way to handle shared logic and potentially reduce the amount of code.

Vue Hooks

Why are Hooks used in Vue? After all, there are no frequently used classes in Vue; In Vue we use mixins to solve the same reuse logic for components;

What’s wrong with mixin? Can Hooks be fixed?

There are two main problems:

  1. Mixins cannot pass state between them;
  2. The logical source is not clearly stated;

Which are well addressed by Hooks;

Here’s an example:

Delivery status

Hooks1

import { useData, useMounted } from 'vue-hooks';

export function windowwidth() {
  const data = useData({
    width: 0
  })

  useMounted(() = > {
    data.width = window.innerWidth
  })

  // this is something we can consume with the other hook
  return {
    data
  }
}Copy the code
  • Hooks2
// the data comes from the other hook
export function logolettering(data) {
  useMounted(function () {
    // this is the width that we stored in data from the previous hook
    if (data.data.width > 1200) {
      // we can use refs if they are called in the useMounted hook
      const logoname = this.$refs.logoname;
      Splitting({ target: logoname, by: "chars" });

      TweenMax.staggerFromTo(".char".5,
        {
          opacity: 0.transformOrigin: "50% 50% -30px".cycle: {
            color: ["red"."purple"."teal"].rotationY(i) {
              return i * 50}}},...Copy the code

Pass values between two hooks:

<script>
import { logolettering } from ". /.. /hooks/logolettering.js";
import { windowwidth } from ". /.. /hooks/windowwidth.js";

export default {
  hooks(){ logolettering(windowwidth()); }}; </script>Copy the code

We can use Hooks composition logic throughout the application;

Source clear

In the SRC /hooks folder, you created a hooks that pauses the page when you open the dialog to view the content, and allows you to scroll again when you have finished viewing the dialog.

It is likely to be used multiple times in an application;

import { useDestroyed, useMounted } from "vue-hooks";

export function preventscroll() {
  const preventDefault = (e) = > {
    e = e || window.event;
    if (e.preventDefault)
      e.preventDefault();
    e.returnValue = false;
  }

  // keycodes for left, up, right, down
  const keys = { 37: 1.38: 1.39: 1.40: 1 };

  const preventDefaultForScrollKeys = (e) = > {
    if (keys[e.keyCode]) {
      preventDefault(e);
      return false;
    }
  }

  useMounted(() = > {
    if (window.addEventListener) // older FF
      window.addEventListener('DOMMouseScroll', preventDefault, false);
    window.onwheel = preventDefault; // modern standard
    window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
    window.touchmove = preventDefault; // mobile
    window.touchstart = preventDefault; // mobile
    document.onkeydown = preventDefaultForScrollKeys;
  });

  useDestroyed(() = > {
    if (window.removeEventListener)
      window.removeEventListener('DOMMouseScroll', preventDefault, false);

    //firefox
    window.addEventListener('DOMMouseScroll'.(e) = > {
      e.stopPropagation();
    }, true);

    window.onmousewheel = document.onmousewheel = null;
    window.onwheel = null;
    window.touchmove = null;
    window.touchstart = null;
    document.onkeydown = null;
  });
} Copy the code

Call it from the appDetails.vue component:

<script>
import { preventscroll } from ". /.. /hooks/preventscroll.js"; .export default{...hooks() {
    preventscroll();
  }
}
</script>Copy the code

summary

  • The original summary

Vue Hooks are already available with Vue 2.x, but are still experimental. We plan to integrate Hooks into Vue 3, but it will still be different from React Hooks;

  • This melon summary

Hooks already apply to Vue3, the setup mess, but it does have some differences from the React Hooks; What’s so great about Vue3? React Hook.

In fact, understand its design intention, even if not the original appropriation of the framework, their own USE of JS native, can also whole a similar reuse logic bar. To package the logic that implements a complete function into a function, read the function name and know what it does. To do so, read the hooks that correspond to it.

I’m Nuggets Anthony, output exposure input, technical insight into life, goodbye ~