Vue3使用Watch监听多个参数

18,683 阅读1分钟

最近做项目的时候遇到了需要用watch监听多个值的问题。

Vue3使用Watch监听当前页面多个值

写法1

const test1 = ref(1)
const test2 = ref(2)
watch(() => [test1.value, test2.value], (newVal, oldVal) => {
    console.log(newVal, oldVal); // [11, 22], [1, 2]
    console.log(newVal[0], oldVal[0], newVal[1], oldVal[1]); // 11, 1, 22, 2
})
// 使用定时器模拟值变化效果
onMounted(() => {
    setTimeout(() => {
        test1.value = 11
        test2.value = 22
    }, 1000)
})

写法2

const test1 = ref(1)
const test2 = ref(2)
watch(() => [test1.value, test2.value], ([preTest1, preTest2], [oldTest1, oldTest2]) => {
    console.log(preTest1, oldTest1, preTest2, oldTest2); // 11, 1, 22, 2
})
// 使用定时器模拟值变化效果
onMounted(() => {
    setTimeout(() => {
        test1.value = 11
        test2.value = 22
    }, 1000)
})