🧠 什么是 Vue 3 中的 Hooks?
在 Vue 3 中,“Hooks” 其实是对组合式 API 的一种使用模式。
它不是 Vue 官方定义的新语法,而是一种用函数封装逻辑、实现复用的习惯写法。
可以理解为:你把 setup() 里的逻辑拆成函数,然后在多个组件中复用这些逻辑。
✅ 为什么需要 Hooks?
传统写法(Options API)中,逻辑分散在 data, methods, computed, watch 中,不好复用。
Vue 3 的组合式 API + Hooks:
- 更容易复用逻辑
- 更容易拆分功能
- 更容易测试
💡 什么时候用 Hooks?
- 多个组件中要复用相同逻辑(比如鼠标坐标、倒计时、API 调用等)
- 想让组件更简洁
🧪 最简单的例子:鼠标位置 Hook
1️⃣ 封装 Hook
// useMouse.ts
import { ref, onMounted, onUnmounted } from 'vue'
export function useMouse() {
const x = ref(0)
const y = ref(0)
function update(e: MouseEvent) {
x.value = e.pageX
y.value = e.pageY
}
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
return { x, y }
}
2️⃣ 在组件中使用
<!-- MouseTracker.vue -->
<template>
<div>Mouse: {{ x }}, {{ y }}</div>
</template>
<script setup lang="ts">
import { useMouse } from './useMouse'
const { x, y } = useMouse()
</script>
📌 核心记忆点
- ✅ Hook = 一个函数
- ✅ 内部用组合式 API(ref、reactive、watch、onMounted 等)
- ✅ 返回的是变量、函数、响应式数据等
- ✅ 在 setup() 或
<script setup>中使用
📦 再举两个实用小例子
✅ useCounter 计数器 Hook
// useCounter.ts
import { ref } from 'vue'
export function useCounter() {
const count = ref(0)
const inc = () => count.value++
const dec = () => count.value--
return { count, inc, dec }
}
使用:
<script setup>
import { useCounter } from './useCounter'
const { count, inc, dec } = useCounter()
</script>
✅ useFetch 获取数据 Hook
// useFetch.ts
import { ref, onMounted } from 'vue'
export function useFetch(url: string) {
const data = ref(null)
const loading = ref(true)
onMounted(async () => {
const res = await fetch(url)
data.value = await res.json()
loading.value = false
})
return { data, loading }
}
🏁 总结一句话:
Vue 3 中的 Hooks 就是组合式 API 的函数封装,用来复用逻辑。写法简单、功能强大。