hooks使用规范及示例
目的
为了维持 模块化 可插拔的特性
使用规范
- 指定模块独有hooks功能
如图,在upms/common下添加hooks目录
- 多模块共享
可以在shares/common目录下创建
示例
以下是一个计时器自定义 Hook 的示例:
ts
import { ref, onMounted, onUnmounted } from 'vue';
export function useTimer() {
const seconds = ref(0);
let timerId = null;
const startTimer = () => {
timerId = setInterval(() => {
seconds.value++;
}, 1000);
};
const stopTimer = () => {
clearInterval(timerId);
timerId = null;
};
onMounted(() => {
startTimer();
});
onUnmounted(() => {
stopTimer();
});
return { seconds, startTimer, stopTimer };
}
// 使用
const { seconds, startTimer, stopTimer } = useTimer();