天天看點

vue3.0之ref函數

vue3.0之ref函數

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);
        }
    }
}      

本文完~

vue3.0之ref函數