This article brings you relevant knowledge about Hooks and vue. Hooks were introduced by React in the V16.7.0-alpha version. Hooks mainly provide a clearer idea for the reuse of patterns. I hope everyone has to help.
Don’t confuse Hooks with Vue’s lifecycle hooks (Lifecycle Hooks). Hooks were introduced by React in the V16.7.0-alpha version, and a few days later Vue releases its proof-of-concept version. Although Hooks were introduced by React, they are a valuable and important composition mechanism for every JavaScript framework ecosystem, so we will spend a little time today discussing what Hooks mean.
Hooks mainly provide a clearer idea for pattern reuse - avoiding rewriting the component itself, and allowing different parts of stateful logic to work together seamlessly.
As far as React is concerned, the problem is this: classes are the most common form of components when it comes to expressing the concept of state. Stateless functional components are also very popular, but since they can only be rendered purely, their use is limited to presentation tasks.
There are some problems with the class itself. For example, as React has become more and more popular, the issue of classes has become a common stumbling block for newbies. In order to understand React, developers must also understand classes. Binding makes the code verbose and less readable, and requires understanding this
in JavaScript. Some of the optimization obstacles presented by using classes are also discussed here.
In terms of logic reuse, we usually use patterns such as render props and higher-order components. But using these patterns can find yourself in a similar "pyramid of doom" - style implementation hell, where excessive use of nesting can lead to components that are difficult to maintain. This leads to me wanting to yell at Dan Abramov like he's drunk, and no one wants that.
Hooks solve these problems by allowing us to define stateful logic for components using function calls. These function calls become more composable, reusable, and allow us to access and maintain state while using functional components. When React released Hooks, there was a lot of excitement - below you can see some of the advantages Hooks demonstrate in terms of how they reduce code and duplication:
When it comes to maintenance, simplicity is key, and Hooks provide a single A functional, functional way to achieve logic sharing, and the amount of code may be smaller.
After reading this you must be wondering what Hooks have to offer in Vue. This seems like a problem that doesn't need to be solved. After all, classes are not the primary pattern used by Vue. Vue provides stateless functional components if you need them, but why do we need to carry state in functional components? We have mixins for combining the same logic that can be reused across multiple components. The problem is solved.
I was thinking the same thing, but after talking to Evan You, he pointed out a major use case that I overlooked: mixins can't consume and use state from each other, but Hooks can. This means that if we need to chain encapsulated logic, we can use Hooks.
Hooks implement the functions of mixins, but avoid the two main problems caused by mixins:
If multiple mixins are used, it is not clear which property is provided by which mixins. Using Hooks, the return value of the function records the consumed value.
So, how does this work in Vue? We mentioned before that when using Hooks, the logic is expressed in function calls and thus reusable. In Vue, this means we can encapsulate a data call, method call, or computed property call into another custom function and make them freely composable. Data, methods, and computed properties are now available for functional components.
Let’s look at a very simple hook so we can understand the building blocks before moving on to the composition examples in Hooks.
Okay, there is a crossover between Vue Hooks and React Hooks. It is a React convention to use use
as a prefix, so if you look for Hooks in React, you will find that the names of Hooks will be like useState
, useEffect
, etc. More information can be found here.
In Evan's online demo, you can see where he accesses useState
and useEffect
for the render function.
If you are not familiar with the render function in Vue, it may be helpful to take a look at the official website documentation.
But when we use Vue-style Hooks, how will we name them - you guessed it - such as: useData
, useComputed
, etc.
So, to give us a look at how to use Hooks in Vue, I created a sample application for us to explore.
In the src/hooks folder, I created a hook that blocks scrolling on the useMounted
hook and re-enables scrolling on the useDestroyed
hook. This helps me pause page scrolling when the dialog box for viewing content is opened, and allows scrolling again when the viewing dialog box ends. This is a good abstraction because it may be used multiple times throughout 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; }); }
Then we can call it in a Vue component like AppDetails.vue:
<script> import { preventscroll } from "./../hooks/preventscroll.js"; ...export default { ... hooks() { preventscroll(); } } </script>
We can not only use it in this component, but also use the same throughout the application Function!
We mentioned before that one of the main differences between Hooks and mixins is that Hooks can actually pass values to each other. Let's look at this simple but somewhat unnatural example.
In our application, we need to perform calculations in a reusable hook, and have something that needs to use the results of that calculation. In our case we have a hook that takes the window width and passes it to the animation so that it knows it will only fire when we are on a larger screen.
See the video demonstration for details: css-tricks.com/wp-content/…
First hook:
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 } }
Then, in the second hook, we Use this to create a condition that triggers the animation logic:
// the data comes from the other hookexport 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 } } }, ...
Then, inside the component, we pass one hook as a parameter to another hook:
<script> import { logolettering } from "./../hooks/logolettering.js"; import { windowwidth } from "./../hooks/windowwidth.js";export default { hooks() { logolettering(windowwidth()); } }; </script>
Now we can use Use Hooks to write logic! Again, this is an unnatural example for demonstration purposes, but you can see how this can be effective for large applications, keeping logic in smaller, reusable functions
[Related recommendations: "vue.js tutorial"]
The above is the detailed content of Let's talk about what Hooks means to Vue. For more information, please follow other related articles on the PHP Chinese website!