watch()简单说明
侦听一个或多个响应式数据源,并在数据源变化时调用所给的回调函数。
侦听单个来源
const count = ref(0)
watch(count, (count, prevCount) => {
/* ... */
})
<script setup>
//导入watch函数
import { ref, watch } from 'vue'
const count = ref(0)
const clickBtn = () => {
count.value++;
}
//输出count变化日志
const msg = ref('count变化情况')
//count:侦听器的源。这个来源可以是以下几种:
//一个函数,返回一个值
//一个 ref
//一个响应式对象
//...或是由以上类型的值组成的数组
//newvalue:变化后的值
//oldvalue:变化前的值
watch(count, (newvalue, oldvalue) => {
msg.value = 'count新值:' + newvalue + ',count旧值:' + oldvalue
})
</script>
<template>
<button @click="clickBtn">{{ count }}</button>
<p>{{ msg }}</p>
</template>
侦听多个来源
当侦听多个来源时,回调函数接受两个数组,分别对应来源数组中的新值和旧值。
<script setup>
//导入watch函数
import { ref, watch } from 'vue'
const count = ref(0)
const changeCount = () => {
count.value++;
}
const name = ref('abc')
const changeName = () => {
name.value = 'eee'
}
//输出count变化日志
const msg = ref('count变化情况')
//侦听方法
watch([count, name], ([newcount, newname], [oldcount, oldname]) => {
msg.value = 'count或者name值发生了变化:新值:' + [newcount, newname] + ',旧值:' + [oldcount, oldname]
})
</script>
<template>
<button @click="changeCount">{{ count }}</button>
<p/>
<button @click="changeName">{{name}}</button>
<p>{{ msg }}</p>
</template>
一次性侦听器