Subscribe on changes!

watchEffect did not perform as expected.

avatar
Mar 1st 2024

Vue version

3.4.21

Link to minimal reproduction

https://play.vuejs.org/#eNp9kstuwjAQRX9l5E1BoFCpXaGA+hCLdtFWbZfeOGYCgcSO/ACkkH/v2BE0ahE7z71nJnccN+yxrpOdRzZlqZWmqB1YdL6ec1VUtTYOGjCYj2EvnFwv8hylgxZyoyu4ob4brriSWlkHAmYBHdwOT0r2T5E9pTdxMBjCbA4NVwBFDgOR7ETpEY5HyLrjEJo2uLIrRyOuWpqRTrrQFJcKh1VdCodUAaSZd04reJBlIbczzgQ1sbmYQtNQ1rZNJx1xmc4inUU6+0vLKEuSQ4TeZ9mYOUur5sUq2Vit6FrjUpxJXdVFiea9dgVdBWc0IjjBE2Wp969Rc8bj+KTLNcrtBX1jD0Hj7MOgRbNDzs6eE2aFrrMXX294oPPZrPTSl0RfMT/R6tKHjB325NWSYve4mPYlPo5Crb7t4uBQ2dNSIWgg28hzRm/k+crqv3HvkvvYRz+WtT+3bNqN

Steps to reproduce

const a = ref(0)
const b = ref(0)
const c = ref(0)
watchEffect(() => {
    c ++
    if(a.value || b.value) {}
})

Modify the values of a and b separately.

What is expected?

Increment c whenever a or b is modified.

What is actually happening?

  • If a is 0, modifying b will trigger c++.
  • If a is not 0, modifying b will not trigger c++.

System Info

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36

Any additional comments?

No response

avatar
Mar 1st 2024
if (a.value >= 0 && b.value >= 0) {}

or

watch([a, b], () => {
  c.value++;
});
avatar
Mar 1st 2024
if (a.value | b.value) {}
avatar
Mar 1st 2024

While I understand that this can be confusing, it's technically working as expected. When the first condition evaluates to false, the code in the second condition won't be run by Javascript, so Vue can't collect b as a dependency of the effect.

Another way to accommodate for this would be to read both values before the condition, i.e.:

https://play.vuejs.org/#eNp9kl9vwiAUxb/KDS/T2NQl25OpZn/iw/awLdvexBiKVKstEKBqUvvdd6HRNZvxrZzzu3AOpSaPWse7SpARSSw3uXZghav0hMq81Mo4qMGILII9c3w9zTLBHTSQGVXCDc7dUEklV9I6YDD2aO+2f1LSfwrvKJ0de70+jCdQUwnQgrMFi2CRzpGfsXjHikpEkLYfc4/lGfQWDI5HpPpQN2G09QcDKhs8IBm2jbALLpwodcGcwBVAklbOKQkPvMj5dkwJwyEyYSOoayzSNMmwJS7TaaDTQKd/aR5kjrKP0DmWRMRZrJflq3hjlcQ7D40p4arUeSHMu3Y51qcEt/CO91hRqP1r0JzBWzjpfC349oK+sQevUfJhhBVmJyg5e46ZlXCtPf16Ewf8PpulWlYF0lfMT2FVUfmMLfZUySXG7nAh7Ut4OblcfdvpwQlpT6V8UE82gacEH9Dzleq/ce/i+zCHP5Y0P79042U=