当 b 更新时 a 并不会更新,因为watchEffect的依赖收集在该案例中停止于await asyncFn(),也就是只会收集同步代码的依赖,await 之后的异步代码的依赖并不会收集到
<template>
<div>a: {{ a }} <br>b: {{ b }} <br><button @click="b++">b++</button>
</div>
</template><script setup lang="ts">
import {ref, watchEffect} from "vue";const a = ref(1);
const b = ref(1);function asyncFn() {return new Promise((resolve) => {resolve(true);})
} watchEffect(async() => {await asyncFn();a.value = b.value;
})
</script>
解决方法1
watchEffect(async() => {a.value = b.value;await asyncFn();
})
解决方法2
watchEffect(async() => {b.value;await asyncFn();a.value = b.value;
})