FE Interview Hub
Vue 3 中階

ref 和 reactive 差異?

AI 練習作答

ref

ref 可用於任何型別(基本型別或物件),存取值需透過 .value

import { ref } from 'vue'

const count = ref(0)
const name = ref('Alice')
const list = ref([1, 2, 3])
const user = ref({ id: 1, name: 'Bob' })

// 讀寫都需要 .value
count.value++
name.value = 'Carol'
user.value.name = 'Dave' // 物件內部屬性不需要 .value

在模板中自動解包(不需要 .value):

<template>
  <p>{{ count }}</p>
  <p>{{ user.name }}</p>
</template>

reactive

reactive 只能用於物件/陣列/Map/Set,存取屬性不需要 .value

import { reactive } from 'vue'

const state = reactive({
  count: 0,
  name: 'Alice',
  list: [1, 2, 3]
})

// 直接存取屬性
state.count++
state.name = 'Carol'

核心比較

特性 ref reactive
適用型別 任何型別 物件、陣列、Map、Set
存取方式 .value 直接存取屬性
解構後響應式 ✅(仍是 ref) ❌(失去響應式)
重新賦值 ✅(直接替換 .value ❌(替換整個物件會失去響應)

reactive 解構問題

const state = reactive({ count: 0, name: 'Alice' })

// ❌ 解構後失去響應式
const { count, name } = state

// ✅ 使用 toRefs 保持響應式
import { toRefs } from 'vue'
const { count, name } = toRefs(state)

官方推薦

Vue 3 官方文件建議:優先使用 ref,因為它更靈活、行為更一致,避免 reactive 的解構陷阱。

✦ AI 模擬面試

輸入你的答案,AI 即時分析精準度與改進空間

登入後即可使用 AI 評分