Skip to content
vue3监听数据的变化
js
<template>
  <section>
    <h2>1. 对象 ref —— 只监听 Client_Value 、RebateType</h2>
    <label>Client_Value:
      <input v-model="forms.Client_Value" />
    </label>
    <label>RebateType:
      <input v-model="forms.RebateType" />
    </label>
    <br>

    <h2>2. 字符串 ref</h2>
    <label>str:
      <input v-model="str" />
    </label>

    <h2>3. 数字 ref</h2>
    <label>num:
      <input type="number" v-model.number="num" />
    </label>

    <h2>4. 数组 ref(push / pop / 直接赋值都能监听到)</h2>
    <button @click="arr.push(Date.now())">push 时间戳</button>
    <button @click="arr.pop()">pop</button>
    <button @click="arr = []">清空</button>
    <p>{{ arr }}</p>
  </section>
</template>

<script setup>
/* eslint-disable no-console */
import { ref, watch } from 'vue'

/* ---------- 1. 对象 ref ---------- */
const forms = ref({
  Client_Value: '',
  RebateType: '',
  DZHFL: '',
  DTBCPFL: ''
})

// 同时监听两个字段
watch(
  [() => forms.value.Client_Value, () => forms.value.RebateType],
  ([newCV, newRT], [oldCV, oldRT]) => {
    console.log('同时监听【forms】Client_Value:', oldCV, '→', newCV)
    console.log('同时监听【forms】RebateType:', oldRT, '→', newRT)
  }
)

// 分别监听
watch(
  () => forms.value.Client_Value,
  (newVal, oldVal) => {
    console.log('只监听Client_Value 变化:', oldVal, '→', newVal)
  }
)

watch(
  () => forms.value.RebateType,
  (newVal, oldVal) => {
    console.log('只监听RebateType 变化:', oldVal, '→', newVal)
  }
)

/* ---------- 2. 字符串 ref ---------- */
const str = ref('hello')
watch(str, (n, o) => console.log('【str】', o, '→', n))

/* ---------- 3. 数字 ref ---------- */
const num = ref(0)
watch(num, (n, o) => console.log('【num】', o, '→', n))

/* ---------- 4. 数组 ref ---------- */
const arr = ref([1, 2, 3])
watch(arr, (n, o) => console.log('【arr】', o, '→', n), { deep: true })
</script>

<style scoped>
label {
  display: block;
  margin: 6px 0;
}
button {
  margin-right: 8px;
}
</style>