西寧網(wǎng)站seo外包360指數(shù)查詢
Vue 3 Hooks 教程
1. 什么是 Hooks?
在 Vue 3 中,Hooks 是一種組織和復(fù)用組件邏輯的強大方式。它們允許您將組件的狀態(tài)邏輯提取到可重用的函數(shù)中,從而簡化代碼并提高代碼的可維護性。
2. 基本 Hooks 介紹
2.1 ref
和 reactive
這兩個函數(shù)是響應(yīng)式數(shù)據(jù)的基礎(chǔ):
import { ref, reactive } from 'vue'// ref 用于基本類型
const count = ref(0)// reactive 用于對象
const state = reactive({name: '張三',age: 25
})
2.2 computed
計算屬性 Hook,用于基于其他響應(yīng)式數(shù)據(jù)創(chuàng)建衍生狀態(tài):
import { ref, computed } from 'vue'const count = ref(0)
const doubleCount = computed(() => count.value * 2)
3. 生命周期 Hooks
Vue 3 提供了多個生命周期相關(guān)的 Hooks:
import { onMounted, onUpdated, onUnmounted } from 'vue'export function useLifecycleDemo() {onMounted(() => {console.log('組件已掛載')})onUpdated(() => {console.log('組件已更新')})onUnmounted(() => {console.log('組件即將卸載')})
}
4. 自定義 Hooks
4.1 創(chuàng)建可復(fù)用的狀態(tài)邏輯
// useCounter.ts
import { ref, computed } from 'vue'export function useCounter(initialValue = 0) {const count = ref(initialValue)function increment() {count.value++}function decrement() {count.value--}const isPositive = computed(() => count.value > 0)return {count,increment,decrement,isPositive}
}
4.2 異步 Hooks
// useFetch.ts
import { ref, computed } from 'vue'export function useFetch(url: string) {const data = ref(null)const error = ref(null)const loading = ref(true)async function fetchData() {try {const response = await fetch(url)data.value = await response.json()loading.value = false} catch (err) {error.value = errloading.value = false}}fetchData()return {data,error,loading}
}
5. Hooks 最佳實踐
- 保持 Hooks 簡單:每個 Hook 應(yīng)該專注于單一功能。
- 命名約定:以
use
開頭,如useCounter
、useFetch
。 - 避免副作用:盡量保持 Hooks 的純凈性。
- 錯誤處理:在 Hooks 中添加適當(dāng)?shù)腻e誤處理機制。
6. 常見 Hooks 示例
6.1 本地存儲 Hook
import { ref, watch } from 'vue'export function useLocalStorage(key: string, initialValue: any) {const storedValue = localStorage.getItem(key)const value = ref(storedValue ? JSON.parse(storedValue) : initialValue)watch(value, (newValue) => {localStorage.setItem(key, JSON.stringify(newValue))}, { deep: true })return value
}
6.2 鼠標位置 Hook
import { ref, onMounted, onUnmounted } from 'vue'export function useMousePosition() {const x = ref(0)const y = ref(0)function update(event: MouseEvent) {x.value = event.pageXy.value = event.pageY}onMounted(() => {window.addEventListener('mousemove', update)})onUnmounted(() => {window.removeEventListener('mousemove', update)})return { x, y }
}
7. 結(jié)論
Vue 3 的 Hooks 為組件邏輯復(fù)用提供了一種強大而靈活的方式。通過合理使用 Hooks,您可以編寫更加模塊化、可讀和可維護的代碼。