前言

目标

1 什么是自定义hook函数
2 hook函数的基本用法


Hook

什么是hook

本质上是一个函数,把setup中使用的 Composition Api进行封装
有点类似于vue2.0中的mixin
优点:复用代码,让setup中的逻辑更清晰易懂

hook的基本用法

在hook文件夹下,封装一个usePoint.js方法
usePoint用来获取鼠标点击时的坐标

import { onMounted,reactive,onBeforeUnmount} from 'vue'
export default function (){
    let point = reactive({
        x:0,
        y:0
    })
    function savePoint(e){
        point.x = e.pageX
        point.y = e.pageY
        console.log(point.x,point.y)
    }
    onMounted(()=>{
        window.addEventListener('click',savePoint)
    })
    onBeforeUnmount(()=>{
        window.removeEventListener('click',savePoint)
    })
    return point
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

在组件中使用usePoint.js方法

import usePoint from '../hooks/usePoint'
setup(){
        let point = usePoint()
        return{
            point
        }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

[Vue3] 7 自定义hook函数_封装