vue3.0之ref函数

web前端开发

共 2083字,需浏览 5分钟

 · 2021-09-14


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

本文完~


学习更多技能

请点击下方公众号



浏览 27
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报