vue3 ref function

1. Ref recommends defining basic data types (ref values ​​can also be objects, but generally it is more reasonable to use reactive directly for objects).

2. When using the ref value in the vue template, you do not need to obtain it through value (vue will automatically add .value to the ref value).

3. The value of ref used in js must be obtained using .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. If you use ref to define complex type data, you will not be able to detect changes in the data. In fact, it will be gone.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. Implementation of ref function

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

Guess you like

Origin blog.csdn.net/weixin_45959525/article/details/120309692