文章目錄 ref 和 reactive 一、差異 二、能否替代的場景分析 (1)基本類型數據 (2)對象類型數據 (3)數組類型數據 (4) 需要整體替換的場景 三、替代方案與兼容寫法 1. 用 reactive 模擬 ref 2. 用 ref 模擬 reactive 四、最佳實踐建議 五、性能對比 六 結論:
ref 和 reactive
一、差異
特性 ref reactive 適用類型 任意類型(包括基本類型) 僅對象/數組 訪問對象 需要通過 .value 直接訪問屬性 整體替換 ?支持(直接賦值) ?不支持(需要特殊處理) 解構保持相應性 ?需要配合 toRef ?需要配合 toRef 性能開銷 較低(僅包裝一層) 較高(深度代理)
二、能否替代的場景分析
(1)基本類型數據
const count = ref ( 0 ) ;
const count = reactive ( 0 ) ;
(2)對象類型數據
const objRef = ref ( { a: 1 } ) ;
const objReactive = reactive ( { a: 1 } ) ;
console. log ( objRef. value. a) ;
console. log ( objReactive. a) ;
(3)數組類型數據
const arrRef = ref ( [ 1 , 2 , 3 ] ) ;
const arrReactive = reactive ( [ 1 , 2 , 3 ] ) ;
arrRef. value. push ( 4 ) ;
arrReactive. push ( 4 ) ;
(4) 需要整體替換的場景
const state = ref ( { a: 1 } ) ;
state. value = { a: 2 } ;
const state = reactive ( { a: 1 } ) ;
state = { a: 2 } ;
三、替代方案與兼容寫法
1. 用 reactive 模擬 ref
const count = reactive ( { value: 0 } ) ;
console. log ( count. value) ;
2. 用 ref 模擬 reactive
const obj = ref ( { a: 1 } ) ;
console. log ( obj. value. a) ;
四、最佳實踐建議
基本類型 → 必須用 ref 對象/數組 → 優先用 reactive(除非需要整體替換) 復雜數據結構 → 混合使用:
const state = reactive ( { count: ref ( 0 ) , user: reactive ( { name: 'Alice' } )
} ) ;
模板中使用 → 優先用 reactive(避免頻繁 .value)
五、性能對比
操作 ref reactive 創建響應式對象 ?快 ??慢 屬性訪問 ???快 ??快 數組修改 ??中 ???快 整體替換 ???快 ?不支持
六 結論:
不能簡單用 reactive 完全替代 ref,但可以根據數據類型和使用場景選擇:
基本類型 → 必須用 ref對象/數組 → 優先用 reactive需要整體替換 → 必須用 ref模板中直接訪問 → 優先用 reactive(減少 .value 噪音)