自定义hook
本质是一个函数,把setup
函数中使用的 Composition API
进行了封装;
类似于2.x中 的mixin
;
自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂;
实现一个获取坐标位置的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <template> <h2>点前点击的鼠标的坐标为x:{{ point.x }},y:{{ point.y }}</h2> </template>
<script>
import { reactive, onMounted,onBeforeUnmount } from "vue"; export default { setup() { 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); console.log(123) }) return { point, }; }, }; </script>
<style> </style>
|
但是这个功能 我如果别的地方也想用,咋办?
新建一个文件夹,起名为hook
,里面新建一个js
文件,起名为usePoint.js
;
将如上实现功能的代码 cv
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| 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; } onMounted(() => { window.addEventListener("click", savePoint); }); onBeforeUnmount(() => { window.removeEventListener("click", savePoint); console.log(123) }) return point; }
|
在需要用这个功能的地方
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <template> <h2>点前点击的鼠标的坐标为x:{{ point.x }},y:{{ point.y }}</h2> </template>
<script>
import usePoint from "../hook/usePoint"; export default { setup() { let point = usePoint();
return{ point, } }, }; </script>
<style> </style>
|