可以把组件中使用组合式API创建的逻辑抽取出来封装成可复用的模块 类似vue2中的mixin
GetMousePoint.js
import {onBeforeUnmount, onMounted, reactive} 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)
})
return point;
}
HelloWorld.vue
import GetMousePoint from "./GetMousePoint"
...
setup() {
let point = GetMousePoint()
return {
point
}
}