Home  >  Article  >  Web Front-end  >  How to use hooks in vue3

How to use hooks in vue3

WBOY
WBOYforward
2023-05-11 22:58:121432browse

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,
  y: Ref
}
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('click', updateMouse)
  })

  onUnmounted(() => {
    document.removeEventListener('click', updateMouse)
  })

  return { x, y }
}

export default useMousePosition

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

// src/views/test.vue


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!

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