Home > Web Front-end > Vue.js > body text

How to use hooks in vue3

WBOY
Release: 2023-05-11 22:58:12
forward
1584 people have browsed it

1. What are hooks

hook means hook. When you see "hook", do you think of hook function? In fact, hooks is really a way of writing functions.

vue3 The Composition API was developed based on react hooks, so it means that the Composition API can also be customized for encapsulation hooks.

hooks

in vue3 is a way of writing functions, which is to extract the js code of some individual functions of the file. Put it in a separate js file, or some public methods/functions that can be reused. In fact, hooks is somewhat similar to mixin in vue2, but compared to mixins, hooks is more clear Use the source of the function code to make it clearer and easier to understand.

2. Usage of hooks

1. Create a hooks folder in src to store hook File

How to use hooks in vue3

2. Write the hook file as needed. For example, if you want to implement a function that records the current position of the mouse when clicking on the page, you can do it in hooks Create a new file useMousePosition.ts in the folder, use of

// src/hooks/useMousePosition.ts
import { ref, onMounted, onUnmounted, Ref } from 'vue'

interface MousePosition {
  x: Ref<number>,
  y: Ref<number>
}
function useMousePosition(): MousePosition {
  const x = ref(0)
  const y = ref(0)

  const updateMouse = (e: MouseEvent) => {
    x.value = e.pageX
    y.value = e.pageY
  }

  onMounted(() => {
    document.addEventListener(&#39;click&#39;, updateMouse)
  })

  onUnmounted(() => {
    document.removeEventListener(&#39;click&#39;, updateMouse)
  })

  return { x, y }
}

export default useMousePosition
Copy after login

3.hook file: use in components that need to use the hook function, such as In the test.vue file:

// src/views/test.vue
<template>
  <div>
    <p>X: {{ x }}</p>
    <p>Y: {{ y }}</p>
  </div>
</template>

<script lang="ts">
import { defineComponent} from &#39;vue&#39;
// 引入hooks
import useMousePosition from &#39;../../hooks/useMousePosition&#39;
export default defineComponent({
  setup () {
    // 使用hooks功能
    const { x, y } = useMousePosition()

    return {
      x,
      y
    }
  }
})
</script>
Copy after login

The above is the detailed content of How to use hooks in vue3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template