hook函数文件:通常在src文件下新建一个hooks文件夹存放不同的hook函数,名称随便起,但是,一般来说,可能会使用use开头命名的文件
// src/hooks/usePageXY.js
import {reactive,onMounted,onBeforeUnmount} from 'vue'
export defalut function usePageXY() {
let point = reactive({
x:0,
y:0
})
function showPoint(event){
point.x = event.pageX
point.y = event.pageY
}
onMounted(()=> {
window.addEventListener('click',showPoint)
})
onBeforeUnmount(()=> {
window.addEventListener('click',showPoint})
})
return point
}
</script>
// src/pages/demo.vue
<template>
<div>x: {{point.x}} ----- y: {{point.y}}</div>
</template>
<script>
import usePageXY from '../hooks/usePageXY'
export default {
name: 'demo1',
setup() {
let point = usePageXY()
return {
point
}
}
}