• hook本质是一个函数,把setup函数中使用到的组合式API进行了封装

  • 把一些逻辑相关的复合到一块,单独写一个js文件,方便其他组件进行引入,实现了代码复用,类似于Vue2的mixin

举例:封装一个鼠标点击,获得点击的x和y轴坐标的hook函数

父组件

<template>
  <div class="App">
    <button @click="handleClick">隐藏/显示Hook组件</button>
    <Hook v-if="isShow"></Hook>
  </div>
</template>
​
<script>
import Hook from '@/components/Hook.vue'
import { ref } from 'vue'
​
export default {
  name: 'App',
  components: {
    Hook,
  },
  setup() {
    let isShow = ref(true)
    function handleClick() {
      isShow.value = !isShow.value
    }
    return {
      isShow,
      handleClick,
    }
  },
}
</script>

子组件

<template>
  <div class="App">
    <h2>当前点击的坐标为 --- X:{
   { point.x }} Y:{
   { point.y }}</h2>
  </div>
</template>
​
<script>
// 这里用到了hooks文件夹下的usePoint.js文件中的usePoint()方法
import usePoint from '@/hooks/usePoint.js'
​
export default {
  name: 'Hook',
  setup() {
    let point = usePoint()
    // console.log(point)
    return { point }
  },
}
</script>

封装的Hook

import { reactive, onMounted, onUnmounted } from 'vue'
​
// 实现鼠标点击的相关
function usePoint() {
  let point = reactive({
    x: 0, // x坐标
    y: 0, // y坐标
  })
  function fn(e) {
    // console.log(e.pageX, e.pageY)
    point.x = e.pageX
    point.y = e.pageY
  }
  onMounted(() => {
    window.addEventListener('click', fn)
  })
  onUnmounted(() => {
    window.removeEventListener('click', fn)
  })
  return point
}
​
export default usePoint

原文链接:https://blog.csdn.net/qq_52845451/article/details/126681227

最后修改:2023 年 10 月 30 日
如果觉得我的文章对你有用,请随意赞赏