vue3.0之ref函数

时间:2021-08-19
本文章向大家介绍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);
        }
    }
}  

  

原文地址:https://www.cnblogs.com/zhaoyd2013/p/15128563.html