Vue3 Hook 实践指南
1. 概述
Vue3 的 Composition API 提供了一种新的方式来组织和管理组件中的状态和行为。
2. 重构状态逻辑
我们可以将组件中的状态逻辑,拆分为可复用的 Hook 函数。
import { ref } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
function increment() {
count.value++
}
return { count, increment }
}
3. 管理副作用
我们可以使用 Hook 来管理组件中的副作用,包括异步请求、定时器、事件监听等。
import { ref, onMounted, onBeforeUnmount } from 'vue'
export function useTimer() {
const count = ref(0)
let timer
function startTimer() {
timer = setInterval(() => {
count.value++
}, 1000)
}
function stopTimer() {
clearInterval(timer)
}
onMounted(() => {
startTimer()
})
onBeforeUnmount(() => {
stopTimer()
})
return { count }
}
4. 命名规范
在编写 Hook 时,我们应该遵循一定的命名规范。通常情况下,我们将 Hook 的名称以 use 开头,以表示这是一个 Hook。此外,我们还应该将 Hook 的名称命名为功能性的,以便于其他开发者理解其作用。