Vue3使用Watch监听多个参数

发表于: 2023-01-08 21:15:34

简介: Vue3使用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)
})

最后更新于:2023-01-08 21:15:34