例如:给组件添加一个监听事件获取鼠标点击事件并复用
①如果不复用的话:(注意,如果不把这个函数单写成savePoint会报错)
②如果需要复用 ,可以进行了封装成hook导出,然后再需要复用的组件中引用就好了。
代码:
usePoint.js
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
console.log(event.pageX, event.pageY)
}
//实现鼠标“打点”相关的生命周期钩子
onMounted(() => {
window.addEventListener('click', savePoint)
})
onBeforeUnmount(() => {
window.removeEventListener('click', savePoint)
})
return point
}
复用usePoint的Demo.vue
<template>
<h2>当前求和为:{{ sum }}</h2>
<button @click="sum++">点我+1</button>
<hr />
<h2>坐标为:x:{{ point.x }},y:{{ point.y }}</h2>
</template>
<script>
import { ref } from "vue";
import usePoint from "../hooks/usePoint";
export default {
name: "Demo",
setup() {
//数据
let sum = ref(0);
let point = usePoint();
//返回一个对象(常用)
return { sum, point };
},
};
</script>
复用复用usePoint的Test.vue
<template>
<h2>我是Test组件</h2>
<h2>坐标为:x:{{ point.x }},y:{{ point.y }}</h2>
</template>
<script>
import usePoint from "../hooks/usePoint";
export default {
name: "Test",
setup() {
const point = usePoint();
return { point };
},
};
</script>