最佳實踐
解構
VueUse 中的大多數函數返回一個 refs 物件,您可以使用 ES6 的物件解構語法來取得您需要的內容。例如
ts
import { useMouse } from '@vueuse/core'
// "x" and "y" are refs
const { x, y } = useMouse()
console.log(x.value)
const mouse = useMouse()
console.log(mouse.x.value)
如果您希望將它們用作物件屬性,您可以使用 reactive()
來解包 refs。例如
ts
import { useMouse } from '@vueuse/core'
import { reactive } from 'vue'
const mouse = reactive(useMouse())
// "x" and "y" will be auto unwrapped, no `.value` needed
console.log(mouse.x)
副作用清理
類似於 Vue 的 watch
和 computed
,當組件卸載時它們會被處置,VueUse 的函數也會自動清理副作用。
例如,useEventListener
將在組件卸載時調用 removeEventListener
。
ts
// will cleanup automatically
useEventListener('mousemove', () => {})
所有 VueUse 函數都遵循此慣例。
為了手動處置副作用,某些函數會像 watch
函數一樣返回一個 stop 處理程序。例如
ts
const stop = useEventListener('mousemove', () => {})
// ...
// unregister the event listener manually
stop()
並非所有函數都返回 stop
處理程序,因此更通用的解決方案是使用 Vue 的 effectScope
API。
ts
import { effectScope } from 'vue'
const scope = effectScope()
scope.run(() => {
// ...
useEventListener('mousemove', () => {})
onClickOutside(el, () => {})
watch(source, () => {})
})
// all composables called inside `scope.run` will be disposed
scope.stop()
您可以在 此 RFC 中了解更多關於 effectScope
的資訊。
響應式參數
在 Vue 中,我們使用 setup()
函數來構建資料和邏輯之間的「連接」。為了使其更靈活,大多數 VueUse 函數也接受 refs 作為參數,因為 refs 是響應式的。
以 useTitle
為例
非響應式參數
useTitle
composable 可幫助您獲取和設置當前頁面的 document.title
屬性。
ts
const isDark = useDark()
const title = useTitle('Hello')
console.log(document.title) // "Hello"
watch(isDark, () => {
title.value = isDark.value ? '🌙 Good evening!' : '☀️ Good morning!'
})
Ref 參數
您可以將 ref 傳遞到 useTitle
中,而不是使用返回的 ref。
ts
const isDark = useDark()
const title = computed(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')
useTitle(title)
響應式 Getter 參數
自 VueUse 9.0 以來,我們引入了一種新的慣例,將「響應式 Getter」作為參數傳遞,這與響應式物件和 Reactivity Transform 非常配合。
ts
const isDark = useDark()
useTitle(() => isDark.value ? '🌙 Good evening!' : '☀️ Good morning!')