Event Hooks 事件处理
概述
Event Hooks 提供事件监听、滚动处理、窗口大小变化等与 DOM 事件相关的功能。
导入方式
import {
useEventListener,
useScroll,
useScrollTo,
useWindowSizeFn,
useBreakpoint,
useIntersectionObserver
} from '@/hooks/event';1. useEventListener 事件监听
自动管理事件监听器的添加和移除,支持防抖和节流。
类型定义
interface UseEventParams {
el?: Element | Ref<Element | undefined> | Window;
name: string;
listener: EventListener;
options?: boolean | AddEventListenerOptions;
autoRemove?: boolean;
isDebounce?: boolean;
wait?: number;
}
function useEventListener(params: UseEventParams): {
removeEvent: () => void;
}基础用法
<script setup lang="ts">
import { ref } from 'vue';
import { useEventListener } from '@/hooks/event';
const count = ref(0);
// 监听窗口点击事件
const { removeEvent } = useEventListener({
name: 'click',
listener: () => {
count.value++;
console.log('窗口被点击');
},
});
// 手动移除事件
// removeEvent();
</script>监听元素事件
<template>
<div ref="wrapperRef" class="scroll-container">
<div class="content">{{ scrollPosition }}</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useEventListener } from '@/hooks/event';
const wrapperRef = ref<HTMLElement>();
const scrollPosition = ref(0);
// 监听元素滚动事件
useEventListener({
el: wrapperRef,
name: 'scroll',
listener: (e: Event) => {
const target = e.target as HTMLElement;
scrollPosition.value = target.scrollTop;
},
});
</script>
<style scoped>
.scroll-container {
height: 200px;
overflow-y: auto;
border: 1px solid #d9d9d9;
}
.content {
height: 1000px;
padding: 20px;
}
</style>使用防抖
<script setup lang="ts">
import { useEventListener } from '@/hooks/event';
// 使用防抖(默认)
useEventListener({
name: 'resize',
listener: () => {
console.log('窗口大小改变(防抖)');
},
isDebounce: true,
wait: 200,
});
</script>使用节流
<script setup lang="ts">
import { useEventListener } from '@/hooks/event';
// 使用节流
useEventListener({
name: 'scroll',
listener: () => {
console.log('页面滚动(节流)');
},
isDebounce: false, // 使用节流
wait: 100,
});
</script>传递选项
<script setup lang="ts">
import { ref } from 'vue';
import { useEventListener } from '@/hooks/event';
const buttonRef = ref<HTMLElement>();
useEventListener({
el: buttonRef,
name: 'click',
listener: (e: Event) => {
e.preventDefault();
console.log('按钮被点击');
},
options: {
passive: false,
once: true,
capture: true,
},
autoRemove: false, // 不自动移除
});
</script>2. useScroll 滚动处理
监听元素的滚动位置。
使用示例
<template>
<div ref="scrollRef" class="scroll-container">
<div class="content">
<p>滚动位置: {{ state.x }}, {{ state.y }}</p>
<p>是否到达底部: {{ isReachedBottom }}</p>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';
import { useScroll } from '@/hooks/event';
const scrollRef = ref<HTMLElement>();
const { state } = useScroll(scrollRef);
const isReachedBottom = computed(() => {
return state.y.value >= 1000;
});
</script>3. useScrollTo 滚动到指定位置
平滑滚动到指定位置或元素。
使用示例
<template>
<div class="scroll-demo">
<div class="sidebar">
<a-button @click="scrollToTop">回到顶部</a-button>
<a-button @click="scrollToElement">滚动到元素</a-button>
<a-button @click="scrollToPosition">滚动到位置</a-button>
</div>
<div ref="containerRef" class="container">
<div class="long-content">
<p v-for="i in 50" :key="i">内容 {{ i }}</p>
</div>
<div ref="targetRef" class="target">目标元素</div>
<div class="more-content">
<p v-for="i in 50" :key="i">内容 {{ i + 50 }}</p>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useScrollTo } from '@/hooks/event';
const containerRef = ref<HTMLElement>();
const targetRef = ref<HTMLElement>();
const { scrollTo } = useScrollTo(containerRef);
// 滚动到顶部
const scrollToTop = () => {
scrollTo({ top: 0, behavior: 'smooth' });
};
// 滚动到元素
const scrollToElement = () => {
if (targetRef.value) {
scrollTo({ el: targetRef.value, behavior: 'smooth' });
}
};
// 滚动到指定位置
const scrollToPosition = () => {
scrollTo({ top: 500, left: 0, behavior: 'smooth' });
};
</script>
<style scoped>
.scroll-demo {
display: flex;
gap: 16px;
}
.sidebar {
position: fixed;
right: 20px;
top: 100px;
display: flex;
flex-direction: column;
gap: 8px;
}
.container {
height: 500px;
overflow-y: auto;
}
.long-content, .more-content {
height: 1000px;
}
.target {
background: yellow;
padding: 20px;
text-align: center;
}
</style>4. useWindowSizeFn 窗口大小变化
监听窗口大小变化并执行回调。
使用示例
<template>
<div class="window-size">
<p>窗口宽度: {{ width }}px</p>
<p>窗口高度: {{ height }}px</p>
<p>是否为移动端: {{ isMobile }}</p>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useWindowSizeFn } from '@/hooks/event';
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);
const isMobile = computed(() => width.value < 768);
onMounted(() => {
useWindowSizeFn(() => {
width.value = window.innerWidth;
height.value = window.innerHeight;
});
});
</script>5. useBreakpoint 响应式断点
获取当前响应式断点。
使用示例
<template>
<div class="breakpoint-demo">
<p>当前断点: {{ currentBreakpoint }}</p>
<p>是否为移动端: {{ isMobile }}</p>
<p>是否为平板: {{ isTablet }}</p>
<p>是否为桌面: {{ isDesktop }}</p>
<!-- 移动端显示 -->
<a-button v-if="isMobile" type="primary">
移动端按钮
</a-button>
<!-- 桌面端显示 -->
<a-space v-else>
<a-button>按钮1</a-button>
<a-button>按钮2</a-button>
<a-button>按钮3</a-button>
</a-space>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { useBreakpoint } from '@/hooks/event';
const screens = useBreakpoint();
const currentBreakpoint = computed(() => {
return Object.keys(screens.value).find(key => screens.value[key]) || 'unknown';
});
const isMobile = computed(() => screens.value.xs || screens.value.sm);
const isTablet = computed(() => screens.value.md);
const isDesktop = computed(() => screens.value.lg || screens.value.xl || screens.value.xxl);
</script>6. useIntersectionObserver 交叉观察器
观察元素是否进入视口。
使用示例
<template>
<div class="observer-demo">
<div class="scroll-area">
<div v-for="i in 5" :key="i" class="section">
<h3>区块 {{ i }}</h3>
<p>内容...</p>
</div>
<div ref="targetRef" class="target-section">
<h3>目标区块</h3>
<p>isVisible: {{ isVisible }}</p>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useIntersectionObserver } from '@/hooks/event';
const targetRef = ref<HTMLElement>();
const isVisible = ref(false);
const { stop } = useIntersectionObserver(
targetRef,
([{ isIntersecting }], observerElement) => {
isVisible.value = isIntersecting;
if (isIntersecting) {
console.log('元素进入视口');
// 停止观察
// stop();
}
},
{
threshold: 0.1, // 10% 可见时触发
}
);
</script>
<style scoped>
.scroll-area {
height: 300px;
overflow-y: auto;
}
.section {
height: 200px;
background: #f5f5f5;
margin-bottom: 16px;
padding: 20px;
}
.target-section {
height: 200px;
background: yellow;
padding: 20px;
}
</style>图片懒加载
<template>
<div class="lazy-load">
<img
v-for="(item, index) in images"
:key="index"
:ref="el => setImageRef(el, index)"
:src="item.visible ? item.src : ''"
:alt="item.alt"
class="lazy-image"
/>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useIntersectionObserver } from '@/hooks/event';
interface ImageItem {
src: string;
alt: string;
visible: boolean;
}
const images = ref<ImageItem[]>([
{ src: '/img1.jpg', alt: '图片1', visible: false },
{ src: '/img2.jpg', alt: '图片2', visible: false },
{ src: '/img3.jpg', alt: '图片3', visible: false },
]);
const setImageRef = (el: any, index: number) => {
if (el) {
useIntersectionObserver(
el,
([{ isIntersecting }]) => {
if (isIntersecting) {
images.value[index].visible = true;
}
},
{ rootMargin: '50px' }
);
}
};
</script>
<style scoped>
.lazy-image {
width: 100%;
height: 300px;
object-fit: cover;
margin-bottom: 16px;
background: #f5f5f5;
}
</style>完整示例
<template>
<div class="event-hooks-demo">
<!-- 滚动监听 -->
<a-card title="滚动监听">
<div ref="scrollContainer" class="scroll-container" @scroll="handleScroll">
<div class="scroll-content">
<p>滚动位置: {{ scrollY }}</p>
<div v-for="i in 20" :key="i" class="item">项目 {{ i }}</div>
</div>
</div>
<a-button @click="scrollToTop">回到顶部</a-button>
</a-card>
<!-- 窗口大小 -->
<a-card title="窗口信息" style="margin-top: 16px">
<p>宽度: {{ windowSize.width }}px</p>
<p>高度: {{ windowSize.height }}px</p>
<p>断点: {{ breakpoint }}</p>
</a-card>
<!-- 可见性 -->
<a-card title="可见性检测" style="margin-top: 16px">
<div class="observer-container">
<div ref="targetRef" class="target-box" :class="{ visible: isVisible }">
{{ isVisible ? '元素可见' : '元素不可见' }}
</div>
</div>
</a-card>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useEventListener, useScrollTo, useWindowSizeFn, useBreakpoint, useIntersectionObserver } from '@/hooks/event';
const scrollContainer = ref<HTMLElement>();
const scrollY = ref(0);
const windowSize = ref({ width: 0, height: 0 });
const targetRef = ref<HTMLElement>();
const isVisible = ref(false);
// 滚动监听
useEventListener({
el: scrollContainer,
name: 'scroll',
listener: (e: Event) => {
const target = e.target as HTMLElement;
scrollY.value = Math.floor(target.scrollTop);
},
});
// 滚动到顶部
const { scrollTo } = useScrollTo(scrollContainer);
const scrollToTop = () => {
scrollTo({ top: 0, behavior: 'smooth' });
};
// 窗口大小
onMounted(() => {
windowSize.value = {
width: window.innerWidth,
height: window.innerHeight,
};
useWindowSizeFn(() => {
windowSize.value = {
width: window.innerWidth,
height: window.innerHeight,
};
});
});
// 断点
const screens = useBreakpoint();
const breakpoint = ref('');
Object.keys(screens).forEach(key => {
if (screens[key]) {
breakpoint.value = key;
}
});
// 可见性
useIntersectionObserver(
targetRef,
([{ isIntersecting }]) => {
isVisible.value = isIntersecting;
},
{ threshold: 0.5 }
);
</script>
<style scoped>
.scroll-container {
height: 200px;
overflow-y: auto;
border: 1px solid #d9d9d9;
}
.scroll-content {
height: 1000px;
}
.item {
padding: 20px;
background: #f5f5f5;
margin-bottom: 8px;
}
.observer-container {
height: 200px;
overflow-y: auto;
}
.target-box {
height: 100px;
margin-top: 150px;
background: #f5f5f5;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s;
}
.target-box.visible {
background: #52c41a;
color: white;
}
</style>注意事项
- 事件清理:组件卸载时自动清理事件监听器
- 性能优化:使用防抖/节流减少高频事件的触发
- 内存泄漏:确保在组件卸载前停止观察器
- 响应式:使用 ref 包裹目标元素
- 阈值设置:IntersectionObserver 的 threshold 应根据实际情况调整
相关文档
- VueUse useEventListener
- Intersection Observer API
- [Core Hooks](../02. CoreHooks/coreHooks.md)
文档版本: 1.0.0 最后更新: 2026-01-10