I have like this code in my project:
JavaScript
x
21
21
1
<script setup>
2
import { ref, watch } from 'vue'
3
4
const num = ref(null)
5
6
// Some condition
7
if(true) {
8
// Doesn't works. Why?
9
num.value = 1
10
11
// Works
12
//setTimeout(() => {
13
// num.value = 2
14
//})
15
}
16
// Simple watcher
17
watch(num, (newVal, oldVal) => {
18
console.log("Num changed to: ", newVal)
19
})
20
</script>
21
My watcher
doesn’t work when I set num.value = 1
. How I can fix this to work?
But when I run with setTimeout
it’s work
Demo project here
Advertisement
Answer
You add the watcher after you set it to 1, so there is no chance for it to catch it.