在 Vue 中,?toRef? 函數用于將響應式對象的屬性轉換為一個獨立的 ?ref? 對象,同時保持與原始屬性的關聯。其參數格式及用法如下:
?toRef? 的參數說明
1. 參數 1:源對象(必須)
- 類型:?Object?(通常是通過 ?reactive? 創建的響應式對象)。
- 作用:指定需要提取屬性的原始對象。
- 示例:
const state = reactive({ count: 0 });
toRef(state, 'count'); // 從 state 對象中提取 count 屬性
?
2. 參數 2:屬性名(必須)
?
- 類型:?String? 或 ?Symbol?。
- 作用:指定需要轉換為 ?ref? 的屬性名稱。
- 示例:
toRef(state, 'name'); // 將 state.name 轉換為 ref 對象
參數使用注意事項
1.?源對象必須是響應式的
- 若源對象不是通過 ?reactive?、?shallowReactive? 等創建的響應式對象,?toRef? 生成的 ?ref? 不會追蹤原始屬性的變化。
const normalObj = { text: '普通對象' };
const textRef = toRef(normalObj, 'text')
normalObj.text = '修改值'; // 不會觸發 textRef 的響應式更新
console.log(textRef.value); // 仍為 '普通對象'
?
2.?屬性不存在時的處理
- 若指定的屬性在源對象中不存在,?toRef? 會創建一個值為 ?undefined? 的 ?ref?,且與源對象無關聯。
const state = reactive({ count: 0 });
const invalidRef = toRef(state, 'invalidProp'); // ref(undefined)
一句話總結
?toRef(obj, key)? 的兩個參數分別是響應式源對象和目標屬性名,用于將對象的屬性轉換為 ?ref?,確保解構或傳遞屬性時保持響應式關聯,是組合式 API 中處理響應式數據的關鍵工具。