watch and watchEffect #12684
Replies: 3 comments
-
Hi @yanzhen222, It seems like if you actually trying to do something with it, except logging it it works well, see this Vue SFC example. It was summed up nicely here:
Originally posted by @LinusBorg in #9773 (comment) |
Beta Was this translation helpful? Give feedback.
-
你想要的结果是什么 |
Beta Was this translation helpful? Give feedback.
-
JavaScript (like many languages) uses short-circuit evaluation for operands of logical operators. So when you write this: if (temp.value >= 60 || height.value >= 80) { If the left-hand operand ( It isn't clear to me what behaviour you want, but I assume you only want to 'send a request' when the condition transitions from There are several ways you could achieve that. For example, you could use a const isEnough = computed(() => temp.value >= 60 || height.value >= 80)
watch(isEnough, (value) => {
if (value) {
console.log('changed')
}
}) You could do something similar with const isEnough = computed(() => temp.value >= 60 || height.value >= 80)
watchEffect(() => {
if (isEnough.value) {
console.log('changed')
}
}) You could also do it using just watch(() => temp.value >= 60 || height.value >= 80, (value) => {
if (value) {
console.log('changed')
}
}) These examples rely on a couple of main ideas:
|
Beta Was this translation helpful? Give feedback.
-
Help!
When using watch to listen, whether temp or height first reaches the condition, it will send a request. As long as the other changes, even if it does not meet the condition, it will also send a request.
Use watchEffect to listen, when temp first reaches the requirement to send a request, then click height, no matter how much will not send a request, but when height first reaches the requirement to send a request, and then change temp, even if it does not meet the condition, will also send a request, may I ask how to solve these situations
Beta Was this translation helpful? Give feedback.
All reactions