First, try calculating properties computed

The first way to write it

<template>
  <div>
    <p><input type="text" v-model="age"></p>
    <p><input type="text" v-model="nextAge"></p>
  </div>
</template>
 
<script>
import { computed, ref } from 'vue'
export default {
  setup() {
    const age = ref(18)
    const nextAge = computed(() => {
      return +age.value + 1
    })
    return {
      age,
      nextAge
    }
  }
}
Copy the code

If you change the age, nextAge automatically +1

However, if nextAge is modified, there is a warning: the calculated properties cannot be modified

The second way to write it

<template> <div> <p><input type="text" v-model="age"></p> <p><input type="text" v-model="nextAge"></p> </div> </template> <script> import { computed, ref } from 'vue' export default { setup() { const age = ref(18) const nextAge = computed({ get() { return +age.value+1 }, set(value) {console.log(value) // Output the new value return age.value = value - 1}}) return {age, nextAge}}}Copy the code

Another way of writing:

For computed and watch, be sure to introduce it first

import { reactive , computed,toRefs,watch} from "vue";
Copy the code

Computed properties

Use the getter function and return an immutable reactive ref object for the value returned from the getter.

As shown in the figure, the case:

{{count}}</p><p>Calculate the value of the property change :{{twoNumber}}</p>
// Reference the ref function to update data in real time
import { defineComponent, reactive , computed,toRefs,watch} from "vue";
export default defineComponent({
  name: "HelloWorld".setup() {
    const state: any = reactive({
      count: 1.twoNumber: computed(() = > state.count*2)});// Expose to the outside world
    // Use toRefs to deconstruct responsive object data for real-time updates
    return {
      ...toRefs(state),
    };
  },
Copy the code

The watch property is exactly equivalent to this.$watch (and the corresponding watch option) in VUe2.

 watch(() = >state.count,(newValue, oldValue) = > {
     console.log('Changed');
     console.log('I'm the new value',newValue);
     console.log('I'm the old value',oldValue);
    })
Copy the code

This is roughly how watch and computed are used in VUE3.

For good suggestions, please enter your comments below.

Welcome to my blog guanchao.site

Welcome to applets: