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方法

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

猜你喜欢

转载自blog.csdn.net/listener_life/article/details/129549139