vue3 客製化hook

vue3 客製化hook

hook理解

  1. 檔案名usexxx開頭。
  2. 把composition api進行封裝。
  3. 類似vue2.0中的mixin。
  4. 更好的複用,邏輯拆分。

代碼

# usePoint.js
import { reactive, onMounted, onBeforeUnmount } from "vue";
export default function () {
    let point = reactive({
        x: 0,
        y: 0
    })
    function savePoint(e) {
        point.x = e.pageX
        point.y = e.pageY
    }
    onMounted(() => {
        window.addEventListener('click', savePoint)
    })
    onBeforeUnmount(() => {
        window.removeEventListener('click', savePoint)
    })
    return point
}

使用

<script>
import usePoint from '@/hooks/usePoint.js'
export default {
  name: "HelloWorld",
  setup() {
    let point = usePoint()
    return {
      point
    }
  }
}
</script>

<template>
  <h2>點擊時鼠標的座標為{{ point.x }} , {{ point.y }}</h2>
</template>