Vue3 hooks

2022/2/8

# EventListener

import { onMounted, onUnmounted } from "vue";
export default function useEventListener(target, event, callback) {
    onMounted(() => target.addEventListener(event, callback));
    onUnmounted(() => target.removeEventListener(event, callback));
}
1
2
3
4
5

# 鼠标位置监测

import { ref } from 'vue';
import useEventListener from './useEventListener'
export default function useMouse() {
    const x = ref(0);
    const y = ref(0);
    function update(e) {
        x.value = e.x;
        y.value = e.y;
    }
    useEventListener(window, 'mousemove', update);
    return { x, y }
}
1
2
3
4
5
6
7
8
9
10
11
12

# 时间格式化

上次更新: 11/1/2024