watch,watchEffect 在异步操作中,它只追踪回调同步执行期间访问的属性,而在异步回调中,只有在第一个 await 之前访问到的依赖才会被追踪。 这是因为watchEffect
和watch
默认只在同步执行期间追踪依赖项的变化。
watchEffect(
async (aaa) => {
const response = await fetch(
`https://img.bosszhipin.com/static/file/2023/${x.value}`
)
console.log('watchEffect', y.value)
}
)
原因:y.value放在 await fetch后面,放它前面就会自动追踪。
下面写法也可以自动追踪
watchEffect(async (aaa) => {
fetch(`https://img.bosszhipin.com/static/file/2023/${x.value}`)
.then((response) => response.json())
.then((json) => console.log(json))
console.log('watchEffect', y.value)
})
下面方法也可以 y.value 肯定为 true,在await前用一下即可
watchEffect(async (aaa) => {
if(y.value) {
fetch(`https://img.bosszhipin.com/static/file/2023/${x.value}`)
.then((response) => response.json())
.then((json) => console.log(json))
}
await nextTick()
// y.value = (await response.json()).nm
console.log('watchEffect', y.value)
})