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
.
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.
1. Create a hooks
folder in src
to store hook
File
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('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 <template> <div> <p>X: {{ x }}</p> <p>Y: {{ y }}</p> </div> </template> <script lang="ts"> import { defineComponent} from 'vue' // 引入hooks import useMousePosition from '../../hooks/useMousePosition' export default defineComponent({ setup () { // 使用hooks功能 const { x, y } = useMousePosition() return { x, y } } }) </script>
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!