自定义 hook 函数
-
什么是 hook?—— 本质是一个函数,把 setup 函数中使用的 Composition API 进行了封装。
-
类似于 vue2.x 中的 mixin。
-
自定义 hook 的优势: 复用代码, 让 setup 中的逻辑更清楚易懂。
实现一个功能点击页面获取点击的坐标轴
<template>
<h1>x轴坐标{{ point.x }}</h1>
<h1>y轴坐标{{ point.y }}</h1>
<button @click="getPoint">获取点击的坐标</button>
</template>
<script>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
export default {
name: "App",
setup() {
let point = reactive({
x: 0,
y: 0,
});
function getPoint(event) {
point.x = event.pageX;
point.y = event.pageY;
}
onMounted(() => {
window.addEventListener("click", getPoint);
});
onBeforeUnmount(() => {
window.addEventListener("click", getPoint);
});
return {
point,
getPoint,
};
},
};
</script>
<style lang="scss"></style>
封装hooks
- 新建hooks文件夹,新建getPoint.js,代码如下
import { reactive, onMounted, onBeforeUnmount } from "vue";
export default function () {
let point = reactive({
x: 0,
y: 0,
});
function getPoint(event) {
point.x = event.pageX;
point.y = event.pageY;
}
onMounted(() => {
window.addEventListener("click", getPoint);
});
onBeforeUnmount(() => {
window.addEventListener("click", getPoint);
});
return point;
}
- 使用
<template>
<h1>x轴坐标{{ point.x }}</h1>
<h1>y轴坐标{{ point.y }}</h1>
</template>
<script>
import getPoint from "./components/hooks/getPoint";
export default {
name: "App",
setup() {
let point = getPoint();
return {
point,
};
},
};
</script>
<style lang="scss"></style>
网友评论