vue3常用响应式对象的api,你全用过了吗?

Ⅰ. ref、reactive ( 递归监听 )

import {ref,reactive} from 'vue';
setup() {
    const num =  ref(123);
    num.value = 456;
     
    const obj = reactive({num:123});
    obj.value = 456;
}
  • ref 对象 在 html 模板中会 自动添加 value ( ref 对象中__v_isRef:true 进行判断的 )
  • ref 对象 => reactive( { value:0 } ) 底层自动转换为 reactive
  • 最终 基本数据 类型采用 => (Object.defineProperty) ,引用数据 类型采用 => ( proxy 代理 )

Ⅱ. isRef、isReactive ( 判断 )

import {isRef,isReactive} from 'vue';
setup() {
        const num = ref(123)
    console.log(isRef(num))  // => true
}
  • 用于判断是否是 Ref 和 Reactive 创建的响应对象
  • 使用场景较少

Ⅲ. toRef 和 toRefs ( 解构 )

toRef (一个属性)

import { toRef , reactive } from 'vue';
setup() {
        const obj = reactive({ width:10, height:20 })
    const width = toRef(obj,'width')
        
        return {
                width
        }
}
  • 将一个响应对象的属性,当作 响应对象 单独拿出来 。

toRefs ( 所有 )

import { toRefs , reactive } from 'vue';
setup() {
        const obj = reactive({ width:10, height:20 })
    const { width, height }= toRefs(obj)
        
        return {
                width, height
        }
}
  • 将多个或所有属性,拿出来 且还是响应对象,
  • 一般在返回的时候一次性全部导出