概述

  1. 监视 ref 定义的基本数据类型.
  2. 监视 ref 定义的对象类型数据,直接写数据名,监视的是对象的地址值,若想监视对象内部的数据,要手动开启深度监视。
监视ref定义的基本数据类型
监视
<template>
  <div class="person">
    <h1>监视 ref 定义的基本数据类型</h1>
    <h2>当前求和为:{{ sum }}</h2>
    <button @click="changeSum">点我 sum + 1</button>
  </div>
</template>

<script lang="ts" setup name="Person">
  import { ref , watch} from 'vue';
  let sum = ref(0);
  function changeSum() {
    sum.value += 1;
  }
  const stopWatch = watch(sum, (newValue, oldValue) => {
    console.log(`sum 发生变化: ${oldValue} -> ${newValue}`);
    if (newValue > 10) {
      stopWatch();
    }
  });
</script>

<style scoped>
  .person {
    background-color: skyblue;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
  }
</style>