[TOC]
- 抽离逻辑代码到一个函数
- 函数命名约为 useXxxx 格式(React Hooks也是)
- 在 setup 中引用 useXxx 函数
案例:获取鼠标所在位置
```vuemouse position
x {{ x }}
y {{ y }}
```javascript
import { ref, onMounted, onUnmounted } from 'vue';
function useMousePosition() {
const x = ref(0);
const y = ref(0);
function update(e) {
x.value = e.pageX;
y.value = e.pageY;
}
onMounted(() => {
console.log('useMousePosition mounted');
window.addEventListener('mousemove', update);
})
onUnmounted(() => {
console.log('remove');
window.removeEventListener('mousemove', update);
})
return { x, y }
}
export default useMousePosition