Vue3 Hooks

灵感借鉴自 React Hooks,但底层原理不同,Vue 基于自身细粒度的响应性系统。

hook:钩子

hooks 是一个函数,被称为“钩子函数”,该函数会和 Vue 组件的特定 API 配合使用,Vue 会在特定时机调用该函数。

特定的时机指:

  • 生命周期函数执行时

  • 某个值改变时

hooks 的优点:

  • 便于代码复用

  • 便于整个逻辑的封装

hooks 相当于组件级别的逻辑封装,比 Vue2 中的 mixins 更加方便好用。

自定义 hooks 函数

约定:hook 文件以 use 开头。

官方示例,该函数可以很方便的给页面添加鼠标监听逻辑。

创建 mouse.js 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 导入Vue组件级相关API
import { ref, onMounted, onUnmounted } from 'vue';
// hook函数命名以use开头
export function useMouse() {
// 响应式数据
const x = ref(0);
const y = ref(0);
// 记录鼠标移动坐标
function update(event){
x.value = event.pageX;
y.value = event.pageY;
}
// 监听组件生命周期
// 添加和移除鼠标移动事件监听器
onMounted(() => window.addEventListener('mousemove', update));
onUnmounted(() => window.removeEventListener('mousemove', update));
// 返回普通对象,内部数据是响应式的,便于解构
return {
x, y
}
}

在组件中使用

1
2
3
4
5
6
7
8
<template>
Mouse position is: {{ x }}, {{ y }}
</template>
<>
<script setup>
import { useMouse } from './mouse.js';
const { x, y } = useMouse();
</script>