vue3实现一个对象引用另一个对象的值且保持响应性

491 阅读1分钟

教女朋友|表弟系列:vue3问题系列

问题背景

某个页面有2个接口,两个接口的参数差不多,所以抽离公共的部分,生成param对象,然后对象里面的值依赖于其他声明的变量,这些变量有些是普通数据类型比如字符串,数字,有些是复杂数据类型,比如对象,数组。并且需要对获取的数据进行二次处理判断,最后才生成真正需要的param

一开始考虑的方向是如何生成一个具备响应性的对象,比如这样:

// 变量
const count = ref(0);
const obj = reactive({
    flag: true, 
    arr: [1, 2]
});

// param
const param = reactive({
  count: ref(count),
  b: toRef(obj, 'flag'),
  a1: toRef(obj.arr, '0'),
  a2: toRef(obj.arr, '1').value > 3 // 这里始终有问题,无法做到响应
});

// 其他操作
const changeResult = () => {
  count.value++;
  obj.flag = !obj.flag;
  obj.arr[0] = 11;
  obj.arr[1] = 22;
};
const showResult = () => {
  console.log({...result})
};

解决方案

采用computed实现。

const count = ref(0);
const obj = reactive({flag: true, arr: [1, 2]});
const changeResult = () => {
  count.value++;
  obj.flag = !obj.flag;
  obj.arr[0] = 11;
  obj.arr[1] = 22
};
const result = computed(() => {
  return {
    count: count.value,
    b: obj.flag,
    a1: obj.arr[0],
    a2: obj.arr[1] > 3
  }
});
const showResult = () => {
  console.log({...result.value})
};