Vue Reactive 使用筆記
使用 Vue 定義資料時,到底要用 ref
還是 reactive
是一個很常見的問題
不過官方文件推薦使用 ref
就行,所以其實也不是甚麼大問題了。( •̀ ω •́ )✧
一般情況下的確 ref
更好,坑也相對少一點,且更容易拆分邏輯,詳細說明可以看看尤大訪談。
所以 reactive
真的沒用用途了嗎?這篇文章來記錄一下 reactive
的用法。
不定期更新,會持續補充用法。( ´ ▽ ` )ノ
解包響應式資料
以 VueUse 的 useElementBounding 為例。
此 API 可以取得多個 element 的 bounding 資料,只需要寬高資料,就可以只取出寬高:
ts
const { width, height } = useElementBounding(el)
但是有時候會需要全部都要,可能會這樣寫:
ts
const bounding = useElementBounding(el)
這時候因為內部資料還是 ref,所以取值需要 .value(例如 bounding.width.value
),這個時候就可以先用 reactive 包起來:
ts
const bounding = reactive(useElementBounding(el))
包起來後,就可以 bounding.width
,不用 value 了
以上用法供大家參考,若有錯誤還請大家多多指教。
建立簡易 store
Vue 官方文件提到 reactive
可以用來建立簡易的 store。
ts
import { reactive } from 'vue'
export const store = reactive({
count: 0,
increment() {
this.count++
}
})
vue
<template>
<button @click="store.increment()">
From B: {{ store.count }}
</button>
</template>
不過除非很原因很明確,否則還是建議使用 Pinia 這類成熟的狀態管理套件,否則未來維護很麻煩。
TIP
這麼做是因為此為內聚性高的獨立元件,若要求使用者在使用此元件前,必須先安裝 Pinia,這樣就太過於繁瑣了。
但若是一般網頁專案,在不確定專案會不會持續增長的情況下,還是建議使用 Pinia。
總結 🐟
- 官方推薦使用 ref
- reactive 可以用在解包響應式資料、建立簡易 store
- 有其他用法也歡迎補充 (´▽`ʃ♡ƪ)