Vue3 的 hook函数

Vue3 的 hook函数 相当于 vue2 的 mixin, 不同在于 hooks 是函数;
Vue3 的 hook函数 可以帮助我们提高代码的复用性, 让我们能在不同的组件中都利用 hooks 函数;
其实就是代码的复用,可以用到外部的数据,生命钩子函数...,具体怎么用直接看代码,

//一般都是建一个hooks文件夹,都写在里面
import {reactive,onMounted,onBeforeUnmount} from 'vue'
export default function (){
   //鼠标点击坐标
   let point = reactive({
      x:0,
      y:0
   })

   //实现鼠标点击获取坐标的方法
   function savePoint(event){
      point.x = event.pageX
      point.y = event.pageY
      console.log(event.pageX,event.pageY)
   }

   //实现鼠标点击获取坐标的方法的生命周期钩子
   onMounted(()=>{
      window.addEventListener('click',savePoint)
   })

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

   return point
}

//在其他地方调用
import useMousePosition from './hooks/useMousePosition'
let point = useMousePosition()


 

猜你喜欢

转载自blog.csdn.net/qq_29528701/article/details/131645250