作用类似于vue2中的mixin技术
案例:获取鼠标点击页面的坐标
1.在src下建hooks文件夹,用于存放复用的js
2.src/hooks/usePoints.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 //注意将point传出去
}
3.要复用的页面
<template>
<div>
<h2>当前点击的坐标 x:{{point.x}},y:{{point.y}}</h2>
</div>
</template>
<script>
import usePoint from '../hooks/usePoint'
export default {
name:'hookView',
setup() {
let point = usePoint()
return {
point,
}
},
}
</script>