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
| import { ref, onMounted, onUnmounted } from 'vue';
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>
|