1.ref推薦定義基本數據類型(ref值也可以是對象,但是一般情況下是對象直接使用reactive更合理)。
2.在 Vue 的模板中使用 ref 的值不需要通過 value 獲取 (Vue 會通過自動給 ref 的值加上 .value)。
3.在 js 中使用 ref 的值必須使用 .value 獲取。
<template> <div>{{count}}</div> </template> <script>
import {ref} from 'vue'
export default { setup(){ const count = ref(10) console.log(count.value) // 10 } } </script>
4.若使用ref定義復雜類型數據,則監聽不到數據的變動
實際是走了reactive (const convert = (val) => isObject(val) ? reactive(val) : val)
<script> import {ref, watch} from 'vue' export default { setup(){ const arr = [1,2,3] setTimeout(() => { arr.value[0] = 0 }, 1500) watch(arr, (nelVal) => { // 監聽不到arr的變化 }) } } </script>
5.ref函數的實現
(1)craeteRef 創建ref對象(將基本數據類型轉為復雜數據類型)
function createRef(rawValue, shallow = false) {
if (isRef(rawValue)) {
return rawValue;
}
return new RefImpl(rawValue, shallow);
}
(2)RefImpl 類(如果傳遞 shallow = true 則只是代理最外層)
class RefImpl {
constructor(value, _shallow = false) {
this._shallow = _shallow;
this.__v_isRef = true;
this._rawValue = _shallow ? value : toRaw(value);
this._value = _shallow ? value : convert(value); // const convert = (val) => isObject(val) ? reactive(val) : val;
}
get value() { // value 屬性訪問器
track(toRaw(this), "get" /* GET */, 'value');
return this._value;
}
set value(newVal) { // value 屬性設置器
newVal = this._shallow ? newVal : toRaw(newVal);
if (hasChanged(newVal, this._rawValue)) { // 判斷新老值是否有變化,改變就更新值,trigger 觸發依賴執行
this._rawValue = newVal;
this._value = this._shallow ? newVal : convert(newVal);
trigger(toRaw(this), "set" /* SET */, 'value', newVal);
}
}
}