---
url: /blog-vue/vue-reactive-cheat-sheet.md
description: 現在官方推薦使用 ref 就行，所以 reactive 還有甚麼用處呢？讓我們筆記一下。(。・∀・)ノ
---

![vue-reactive-cheat-sheet](/vue-reactive-cheat-sheet.webp){.cover}

# Vue Reactive 使用筆記

使用 Vue 定義資料時，到底要用 `ref` 還是 `reactive` 是一個很常見的問題

不過[官方文件推薦使用 `ref`](https://vuejs.org/guide/essentials/reactivity-fundamentals#limitations-of-reactive:~:text=Due%20to%20these%20limitations%2C%20we%20recommend%20using) 就行，所以其實也不是甚麼大問題了。%( •̀ ω •́ )✧%

一般情況下的確 `ref` 更好，坑也相對少一點，且更容易拆分邏輯，詳細說明可以看看[尤大訪談](https://www.youtube.com/watch?v=e8Wlv4AGJjk\&ab_channel=%E6%88%90%E5%BC%8F%E8%AA%9E%E8%A8%80%2FMikeCheng)。

之前看到有人分享：「統一使用 `ref` 的優點是可以明確區分資料，需要用 `.value` 存取的資料一定為響應式資料，反之則否」，我覺得這個準則確實有幫助。

所以 `reactive` 真的沒用用途了嗎？這篇文章來記錄一下 `reactive` 的用法。

不定期更新，會持續補充用法。%( ´ ▽ \` )ﾉ%

## 解包響應式資料

以 VueUse 的 [useElementBounding](https://vueuse.org/core/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 官方[文件](https://vuejs.org/guide/scaling-up/state-management#simple-state-management-with-reactivity-api)提到 `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
我曾經在[酷酷元件的落雪元件](https://chillcomponent.codlin.me/components/bg-snow/)中[實作過此用法](https://gitlab.com/side_project/chill-component/-/blob/main/src/components/bg-snow/bg-snow-store.ts)。

這麼做是因為此為內聚性高的獨立元件，若要求使用者在使用此元件前，必須先安裝 Pinia，這樣就太過於繁瑣了。

但若是一般網頁專案，在不確定專案會不會持續增長的情況下，還是建議使用 Pinia。
:::

## 總結 🐟

* 官方推薦使用 `ref`
* `reactive` 可以用在解包響應式資料、建立簡易 store
* 有其他用法也歡迎補充 %(´▽\`ʃ♡ƪ)%
