Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  186] [ 4]  / answers: 1 / hits: 6574  / 2 Years ago, thu, may 19, 2022, 12:00:00

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.


More From » vue.js

 Answers
1

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.


[#134] Tuesday, May 3, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
Thu, Apr 1, 21, 00:00, 3 Years ago
Mon, Jul 27, 20, 00:00, 4 Years ago
Wed, Feb 12, 20, 00:00, 4 Years ago
;