侦听源数据类型
ref 或 reactive
vue
<template>
<div class="div-box">
<input type="number" v-model="xRef" />
<p>X Msg: {{ xMsg }}</p>
<p>Y=2X Msg: {{ yMsg }}</p>
</div>
</template>
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
const xRef = ref(0)
const xMsg = ref('X is not changed')
const yMsg = ref('Y is not changed')
watch(xRef, (newX, oldX) => {
xMsg.value = `X changed from ${oldX} to ${newX}`
})
const y = computed(() => xRef.value * 2)
watch(y, (newY, oldY) => {
yMsg.value = `Y changed from ${oldY} to ${newY}`
})
</script>
getter 函数
vue
<template>
<div class="div-box">
<input type="number" v-model="x" />
<input type="number" v-model="y" />
<p>{{ msg }}</p>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
const x = ref(0)
const y = ref(0)
const msg = ref('X + Y is not changed')
watch(
() => x.value + y.value,
(newVal, oldVal) => {
msg.value = `X + Y changed from ${oldVal} to ${newVal}`
}
)
</script>
多个侦听源
vue
<template>
<div class="div-box">
<input type="number" v-model="x" />
<input type="number" v-model="y" />
<p>{{ msg }}</p>
</div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
const x = ref(0)
const y = ref(0)
const msg = ref('X + Y is not changed')
watch([x, () => y.value], ([newX, newY], [oldX, oldY]) => {
msg.value = `X + Y changed from ${oldX} + ${oldY} to ${newX} + ${newY}`
})
</script>