vue3的hook类似于vue2的Mixin(混入)
// src/hooks/usePoint.js
import {reactive, onMounted, onBeforeMount} from 'vue'
export default function() {
let point = reactive({
x: 0,
y: 0
})
function pointEvent(event) {
point.x = event.pageX
point.y = event.pageY
}
onMounted(() => {
window.addEventListener('click', pointEvent)
})
onBeforeMount(() => {
window.removeEventListener('click', pointEvent)
})
return point
}
// src/components/Demo.vue
<template>
<h1>鼠标点击处的坐标为:x={{point.x}}, y={{point.y}}</h1>
</template>
<script>
import usePoint from '../hooks/usePoint'
export default {
name: 'Demo',
setup() {
let point = usePoint()
return {
point
}
},
}
</script>