- 抽离逻辑代码到一个函数
- 函数命名约定为useXxxx格式(react Hooks也是)
- 在setup中去引用这个函数
如下经典鼠标位置例子:
// useMousePosition.ts
import { onMounted, onUnmounted, ref } from "vue";
const useMousePosition = () => {
const x = ref(0);
const y = ref(0);
function mousemoveHandler(e: MouseEvent) {
x.value = e.pageX;
y.value = e.pageY;
}
onMounted(() => window.addEventListener('mousemove', mousemoveHandler));
onUnmounted(() => window.removeEventListener('mousemove', mousemoveHandler));
return { x, y }
}
export default useMousePosition;
// index.vue
<template>
<div>
position - x: {{ x }}, y: {{ y }}
</div>
</template>
<script lang="ts">
import useMousePosition from './useMousePosition';
export default {
setup() {
const { x, y } = useMousePosition()
return {
x,
y
}
}
}
</script>