<template>
  <div>Case of actual combat</div>
  <hr>
  <button @click="age=25">Click on the</button>
  <div>{{age}} years old this year</div>
  <div>{{nextAge}} years old next year</div>
</template>
Copy the code
 // Introduce ref and computed
import { ref, computed } from 'vue'
export default {
  name: 'App',
  setup () {
  // age The initial value is 18
    const age = ref(18)
    // Change to next year 19 using calculated attributes
    const nextAge = computed(() = > {
      return age.value + 1
    })
    After being used in the setup function, it must return to be used in the template
    return { age, nextAge }
  }
} 
Copy the code

The calculated property cannot be modified directly because it is read-only.

For computed propertiesget(){}andset(){}Method with modify calculated properties, use it to modify the value of calculated properties!

Be sure to note here:

Call the computedgetandsetA method is an object mode, not a callback function

The set method:

<template>
  <div>Case of actual combat</div>
  <hr>
  <button @click="age=25">Click on the</button>
  <button @click="nextAge=28">Modify the</button>
  <div>{{age}} years old this year</div>
  <div>{{nextAge}} years old next year</div>
</template>
Copy the code
import { ref, computed } from 'vue'
export default {
  name: 'App',
  setup () {
    const age = ref(18)
    const nextAge = computed({
      get () {
      // When I want to read the value of a calculated property, the default call is get
        return age.value + 1
      },
      // The parameter v is the value you pass in
      set (v) {
        // When I want to change the value of the calculated property, the default call is set
        // console.log(v)
        age.value = v - 1}})return { age, nextAge }
  }
}
Copy the code