ref、reative结合hooks的用法

142 阅读1分钟

一、字节组件库中经常看到这种写法,为什么要这么写???

image.png

先看一段代码

const num = ref(1); 
const arrNum = ref([0, 1]); 

const result1 = reactive({ num, arrNum }); 
const result2 = reactive([ref(0),1]); 

console.error(result1.num, result1.arrNum[0], result2[0].value); // 1 0 0

为什么结果会这样?

解释:

1、reactive的入参为数组类型 =》原封不动的返回,不做处理

2、reactive的入参为对象类型 =》如果对象中有为ref类型的且数据源不是数组,则取值时会自动补充.value

image.png

可以做什么?

vue中自定义hooks时,内部调用参数统一

需要开发者记住参数是ref还是reactive类型,使用时体验感不好。举例如下:ref类型需要.value

function useHooks(options) {
    options.ref1.value;
    options.ref2.value;
    options.reactive1.a;
    options.reactive1.b;
}

const ref1 = ref(1);
const ref2 = ref(2);
const reactive1 = reactive({
    a: 1,
    b: 2
});
useHooks({ ref1, ref2, reactive1 });

reacitve包裹一下,就不需要开发者记住是.value还是reactive,直接使用即可。举例如下:

// 方式一
function useHooks(options) {
    options.ref1;
    options.ref2;
    options.reactive1.a;
    options.reactive1.b;
}

// 方式二
function useHooks1(options) {
    const { ref1, ref2, reactive1 } = toRefs(options);
    ref1.value;
    ref2.value;
    reactive1.value.a;
    reactive1.value.b;
}

const ref1 = ref(1);
const ref2 = ref(2);
const reactive1 = reactive({
    a: 1,
    b: 2
});

// reactive包裹一下
useHooks(reactive({ ref1, ref2, reactive1 }));