最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to watch for multiple values in Vue 3 script setup? - Stack Overflow

programmeradmin1浏览0评论

I have this watcher (inside <script setup>:

const form = reactive({
    body: '',
    image: ''
})

watch(() => form.image, () => {
    console.log(form.image)
})

which I want to expand to watch two reactive objects:

watch(() => (form.image, form.body), () => {
    console.log(form)
})

but this now only watches form.body. I've been trying to implement this question's answer, but it doesn't seem to work like my watcher with new and old values. I want the watcher to trigger, when both values are updated.

I have this watcher (inside <script setup>:

const form = reactive({
    body: '',
    image: ''
})

watch(() => form.image, () => {
    console.log(form.image)
})

which I want to expand to watch two reactive objects:

watch(() => (form.image, form.body), () => {
    console.log(form)
})

but this now only watches form.body. I've been trying to implement this question's answer, but it doesn't seem to work like my watcher with new and old values. I want the watcher to trigger, when both values are updated.

Share Improve this question edited May 19, 2022 at 13:22 Artur Müller Romanov asked May 19, 2022 at 13:16 Artur Müller RomanovArtur Müller Romanov 5,77119 gold badges108 silver badges190 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 11

I figured something out. It'll trigger when both values are true. You can put your own conditions in there.

const form = reactive({
    body: '',
    image: ''
})

watch(() => [form.image, form.body], () => {
    if (form.image && form.body) {
        console.log(form)
    }
})
This seems to work for simple cases but when the code base gets large and using `global proxies` (like a reactive store) as well as using too many proxies, it can fail. I've tried it with 4 global proxies on a large project and it only triggered sometimes.

Like @tao suggested in the comments, if you're working with nested objects, you have to use { deep: true } in your watcher.

More about deep watchers in the vue docs.

You need to call watch each time if you need multiple watchers:

watch(() => form.image, () => {
    console.log(form.image)
})
watch(() => form.body, () => {
    console.log(form.body)
})

if what you need is a watcher to watch the two then :

watch([() => form.image, () => form.body], 
([newImage, newBody], [prevImage, prevBody]) => {
    console.log(form.body, form.image)
})

if we take example on that answer : https://stackoverflow.com/a/45853349/8126784 from the question you linked

This can be done with watchEffect it will check the reactivity:

watchEffect(() => {
  emit('update:selectedProduct', localSelectedProduct.value);
  emit('update:selectedOffer', localSelectedOffer.value);
});

Here's the vuejs docs: https://vuejs.org/guide/essentials/watchers.html#watcheffect

发布评论

评论列表(0)

  1. 暂无评论