Home  >  Article  >  Web Front-end  >  Learn more about Hooks in Vue and talk about its significance to Vue!

Learn more about Hooks in Vue and talk about its significance to Vue!

青灯夜游
青灯夜游forward
2022-02-10 18:56:0113296browse

What do hooks mean for Vue? This article will take you to understand Hooks in Vue and talk about its significance for Vue. I hope it will be helpful to everyone!

Learn more about Hooks in Vue and talk about its significance to Vue!

The Hooks we are going to talk about in this article are different from Lifecycle Hooks (life cycle hooks), which were introduced into React in v16.7.0-alpha ;Although Hooks was proposed by React, its essence is an important code combination mechanism, which is of great benefit to the entire JavaScript framework system; take a moment to talk about it in detail today: What does Hooks mean to Vue? ?

Hooks provide a clearer way to organize code, make code reusable, and more importantly, allow different logical parts to communicate and work together. [Related recommendations: vue.js video tutorial]

Problem background

Why were Hooks raised? As far as React is concerned, the original background of the problem is this:

When it comes to expressing the concept of state, Classes are the most common organizational form. The class itself has some problems, such as long and complicated binding relationships, making it difficult to read, and the direction of This always makes people confused;

Not only that, in terms of reuse, use rendering tools or high-order components The class pattern is very common, but it is easy to fall into the "pyramid of doom" (Pyramid of Doom), which can be understood as excessive nesting relationships;

Hooks are here to solve these problems ; Hooks allow us to use function calls to define the state logic of components. These functions are more composable and reusable; at the same time, state access and maintenance can still be performed;

Example: @dan_abramov's code from #ReactConf2018

  • Picture①

Learn more about Hooks in Vue and talk about its significance to Vue!

  • Picture②

Learn more about Hooks in Vue and talk about its significance to Vue!

There is a transition from Figure ① to Figure ②, the component code is recombined, and then exported as a function for external reuse;

In terms of maintenance, Hooks Provides a single, functional way to handle shared logic with the potential to reduce code size.

Vue Hooks

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

What is the problem with mixins? Can Hooks solve it?

There are two main problems:

  • mixins cannot transfer state;

  • There is no clear explanation of the logical source ;

Hooks can solve these two points very well;

For example:

Transfer 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
  }
}
  • 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
            }
          }
        },
        ...

Passing values ​​between two hooks:

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

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

We can use it throughout the application Hooks combination logic;

Clear source

In the src/hooks folder, a Hooks is created to implement: pausing the page when opening the dialog box to view the content , and allow scrolling again after viewing the dialog box.

It is likely to be used multiple times in the 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;
  });
}

Call it in the AppDetails.vue component:

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

export default {
  ...
  hooks() {
    preventscroll();
  }
}
</script>

Summary

  • Original summary

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

  • Summary of this article

Hooks has been applied to Vue3 , that is, the setup thing, but it does have some differences from React's Hooks; it is recommended to read What is the advantage of Vue3? (Detailed comparison with React Hook)

Address https://zhuanlan.zhihu.com/p/133819602

In fact, I understand its design intention, even if it is not original By appropriating the framework and using JS natively, you can create a similar reuse logic. Encapsulate the logic that implements a complete function into a function. Just look at the function name and you will know what it does. You don’t need to know its internal implementation. If you want to know, go to the corresponding hooks to find it. At least this is it. In a sense, it is consistent with functional programming design ideas;

The main body of this article is translated from: what-hooks-mean-for-vue (https://css-tricks.com/what -hooks-mean-for-vue/)

Author: Sarah Drasner

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of Learn more about Hooks in Vue and talk about its significance to Vue!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete