什么是hook?———本质是一个函数,把setup函数中使用的组件式api简写了封装
也就是说将一段复杂的代码逻辑,抽分到一个js中,其他地方需要使用就进行引入即可
如在src下的hook文件夹中的userPoint.js
import {
reactive,
onMounted,
onBeforeUnmount
} from 'vue'
export default function () {
//实现鼠标打点的数据
const point = reactive({
x: 0,
y: 0
});
//实现鼠标打点的方法
function savePoint(event) {
point.x = event.pageX;
point.y = event.pageY;
console.log(point.x,point.y);
}
// 使用 onMounted 钩子来添加事件监听器
onMounted(() => {
window.addEventListener('click', savePoint);
});
// 使用 onBeforeUnmount 钩子来移除事件监听器
onBeforeUnmount(() => {
window.removeEventListener('click', savePoint);
});
return point
}
在Demo.vue中进行引入
<template>
<h2>当前求和为:{{ sum }}</h2>
<button @click="sum++">点我加1</button>
<br />
<h2>当前点击时鼠标的坐标为:x:{{ point.x }},y:{{ point.y }}</h2>
</template>
<script>
import {
ref,
} from "vue";
import usePoint from '../hooks/usePoint'
export default {
name: "Demo",
setup() {
console.log('---setup---');
const sum = ref(0);
let point=usePoint()
return { sum,point};
},
};
</script>
<style>
</style>