[Vue3] computed property

computed computed properties

A computed property triggers its change when the value of the dependent property changes. If the dependent value does not change, the property value in the cache is used

  • Create a read-only computed property ref:
<script setup lang="ts">
import {
    
     computed, reactive, ref } from 'vue'
let state = ref(0)
let num =  computed<number>(() => state.value)
num.value++ // 错误
console.log(num.value) // 0
  </script> 
  • Create a writable computed property ref:
<script setup lang="ts">
import {
    
     computed, reactive, ref } from 'vue'
let state = ref(0)
let num =  computed({
    
    
  get: () => state.value + 1,
  set: (val) => {
    
    
    state.value = val - 1
  }
})
console.log(num.value) // 1
console.log(state.value) // 0
  </script> 

Guess you like

Origin blog.csdn.net/weixin_50636536/article/details/128364637