跳至主要内容

2 篇文章 含有標籤「reactive」

檢視所有標籤

Vue ref 與 reactive 入門教學筆記 | 學習筆記

· 閱讀時間約 2 分鐘
kdchang

前言

在 Vue 3 中,refreactive 都是用來創建響應式資料的工具,但它們適用的情境略有不同。以下是清楚的比較與實際使用範例,幫助你理解什麼時候該用哪一個。


ref 使用情境

適用於:

  • 原始資料型別:如 NumberStringBooleanDate 等。
  • 你只需要追蹤單一值。
  • 當你需要某個變數傳遞到 <template> 或函式中。

語法:

import { ref } from 'vue'

const count = ref(0)
count.value++ // 需要用 .value 訪問或修改

範例:

<script setup>
import { ref } from 'vue'

const message = ref('Hello')
const count = ref(0)

const updateMessage = () => {
message.value = 'Hi Vue 3'
}
</script>

reactive 使用情境

適用於:

  • 物件或陣列:需要操作多個屬性的資料結構。
  • 多層巢狀資料或你希望所有屬性都具有響應性。
  • 表單資料、設定物件等複雜狀態管理。

語法:

import { reactive } from 'vue'

const user = reactive({
name: 'Daniel',
age: 30
})

user.age++ // 直接修改即可,無需 .value

範例:

<script setup>
import { reactive } from 'vue'

const form = reactive({
username: '',
email: '',
isSubscribed: false
})

const submitForm = () => {
console.log(form.username, form.email, form.isSubscribed)
}
</script>

⚠️ ref 包物件 vs reactive

雖然你也可以這樣用:

const user = ref({ name: 'Daniel', age: 30 })

但要存取時就需要:

user.value.name = 'John'

reactive 則可以直接操作:

user.name = 'John'

所以若你有物件資料,通常選擇 reactive 更直覺。


建議使用方式整理:

類型建議使用方式
單一變數(數字、字串)ref
多欄位表單資料reactive
陣列、物件、巢狀結構reactive
要被 watchcomputed 的原始值ref

Vue pinia 保持 reactive 入門教學筆記 | 學習筆記

· 閱讀時間約 2 分鐘
kdchang

保持 reactive 寫法:


1️. 用 computed

const todos = computed(() => todoStore.todos)

優點

  • 保持 reactive
  • 簡單直接
  • 在 template 裡 todos 可以直接使用

缺點

  • 如果只是讀值,其實有點多餘

建議用於:在 template 需要用 v-for="todo in todos" 這種情況下。


2️. 直接使用 todoStore.todos 在 template

不額外宣告變數,直接寫:

<ul>
<li v-for="todo in todoStore.todos" :key="todo.id">
{{ todo.text }}
</li>
</ul>

優點

  • 直接讀取 store,最簡單
  • 不需要 computed

缺點

  • 如果在 script 多處使用 todos,每次都要寫 todoStore.todos

建議用於:只在 template 需要使用 todos 的情況。


3️. 使用 storeToRefs

這是 Pinia 官方推薦的方式,可以一次把 state 解構成 reactive ref:

import { storeToRefs } from 'pinia'

const todoStore = useTodoStore()
const { todos } = storeToRefs(todoStore)

優點

  • todos 是 reactive
  • 取值時不會失去 reactive
  • 適合同時取多個 state(例如 const { todos, count } = storeToRefs(todoStore)

缺點

  • 需要額外 import storeToRefs
  • 初學者可能不熟悉

建議用於:component 中需要多個 state 且偏好解構寫法時。


寫法比較

寫法是否 reactive適用場景
computed 包一層script 內多次使用
直接 todoStore.todos只在 template 使用
storeToRefs多個 state 解構需要時

建議

  • 如果只需要一個 state:computed 或直接用 todoStore.todos
  • 如果需要多個 state:storeToRefs

範例(使用 storeToRefs

<script setup>
import { useTodoStore } from '../stores/todoStore'
import { storeToRefs } from 'pinia'

const todoStore = useTodoStore()
const { todos } = storeToRefs(todoStore)

function addTodo() { ... }
function removeTodo(id) { ... }
function toggleComplete(id) { ... }
</script>

template 裡直接使用 todos,效果與 computed 相同。


總結
三種寫法都可行,主要差異在語法風格與使用場景。若不想意外解構成非 reactive 值,使用 storeToRefs 是最安全的。