vue3中computed的使用详解

<my-card class="card">
    <h2 class="title">测试computed的get、set方法</h2>
    <el-button @click="testComputed">点击获取新值</el-button>
</my-card>

// 测试computed的get、set方法
const propsValue = ref({
  a: 1,
  b: 2,
  c: { aa: 55, bb: 66 }
})
const computedValue = computed({
  get: () => {
    console.log('触发get方法')
    return JSON.parse(JSON.stringify(propsValue))
  },
  set: val => {
    console.log('触发set方法')
  }
})

const testComputed = () => {
  // propsValue.value.a = Math.random() // 执行该代码时,会触发 computed的 get 方法

  computedValue.value.c = { // 执行该代码时,不会触发 computed的set方法
    aa: 555,
    bb: 666
  }
  
  // computedValue.value = { // 执行该代码时,会触发computed的set方法
  //   a: 11,
  //   b: 2,
  //   c: 3
  // }
}

根据以上代码说明,在vue3中,

        computed的get方法触发条件为:

                当computedValue依赖的值改变时,就会触发get方法,

        computed的set方法触发条件为:

                当改变整个computedValue对象时,才会触发set方法,改变computedValue对象的某个属性的值时,不会触发set方法

以上内容纯属个人开发过程中遇到的问题及总结,如有错误,可联系博主修改,非常感谢!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值