Vue3.0 watch监听ref定义的响应式数据变化

<template>
  <div>
    <h3>num1:{{ num1 }}</h3>
    <h3>num2:{{ num2 }}</h3>
    <button @click="add"></button>
  </div>
</template>
<script>
import { ref, computed, watch } from "vue";
export default {
  setup() {
    let num1 = ref(0);
    let num2 = ref(1);

    function add() {
      num1.value = num1.value + 1;
      num2.value = num2.value + 2;
    }
    // 情况一 : 监听一个ref定义的响应式数据变化
    watch(num1, (val) => {
      console.log(val);
      console.log(`num1: ${val}`);
    });
    //情况二 :监听多个ref定义的响应式数据变化
    watch([num1, num2], (val) => {
      console.log(val);
      console.log(`num1: ${val[0]}`);
      console.log(`num2: ${val[1]}`);
    });
    return { num1, num2, add };
  },
};
</script>

你可能感兴趣的:(Vue3.0从入门到放弃)