【Vue3】自定义hook函数

1、什么是hook?

           本质是一个函数,把setup函数中使用的Composition API进行了封装

2、类似于vue2.x中的mixin

3、自定义hook的优势:复用代码,让setup中的逻辑更加清楚

举例:在HelloWorld中复用hooks文件夹中的usePonit函数 

【Vue3】自定义hook函数_第1张图片

 usePoint.js

import { onMounted, reactive, onBeforeUnmount} from 'vue'
export default function(){
  

    //实现鼠标打点的数据
    let point =reactive({
      x:0,
      y:0
    })
    
    //实现鼠标点击获取坐标的方法
    function savePoint(event){
        point.x=event.pageX
        point.y=event.pageY
      }
    
    onMounted(()=>{
        window.addEventListener('click',savePoint)
      })

    onBeforeUnmount(()=>{
        window.removeEventListener('click',savePoint)

      })
    
    //返回一个对象(常用)

      return point

  }

HelloWorld.vue








 

你可能感兴趣的:(Vue,前端,javascript,开发语言,vue.js)