watch and watchEffect #12684
-
Help! <template>
<div class="person">
<h2>temp:{{ temp }}℃</h2>
<h2>height:{{ height }}cm</h2>
<button @click="changeTemp" >temp+10</button>
<button @click="changeHeight" >height+10</button>
</div>
</template>
<script lang="ts" setup name="Person234">
import { ref, watch, watchEffect } from "vue";
let temp = ref(10)
let height = ref(0)
function changeTemp(){
temp.value += 10
}
function changeHeight(){
height.value += 10
}
watch([temp,height],(value)=>{
let [newTemp,newHeight] = value
// console.log(newTemp,newHeight)
if (newTemp >= 60 || newHeight >= 80) {
console.log('changed')
}
})
// watchEffect(()=>{
// if (temp.value >= 60 || height.value >= 80) {
// console.log('changed')
// }
// })
</script>
<style scoped>
.person {
background-color: #363d9b;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin: 0 5px;
}
li {
font-size: 20px;
}
</style>
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
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.
JavaScript (like many languages) uses short-circuit evaluation for operands of logical operators.
So when you write this:
If the left-hand operand (
temp.value >= 60
) is truthy, it won't evaluate the right-hand operand (height.value >= 80
). As a result,height.value
won't be tracked as a dependency ofwatchEffect
and changes toheight.value
won't have any impact.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
false
totrue
.There are several ways you could achieve that. For example, you could use a
computed
: