Detailed explanation of the use of computed in vue3

<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
  // }
}

According to the above code description, in vue3,

        The trigger conditions for the computed get method are:

                When the value that computedValue depends on changes, the get method will be triggered.

        The trigger conditions for computed's set method are:

                The set method will only be triggered when the entire computedValue object is changed. When the value of a certain attribute of the computedValue object is changed, the set method will not be triggered.

The above content is purely based on the problems and summary encountered during personal development. If there are any errors, you can contact the blogger for modification. Thank you very much!

Guess you like

Origin blog.csdn.net/listener_life/article/details/129549139