为什么道具的 Vue3 观察者不会被触发?(组合 API)

WoJ*_*WoJ 1 watch vue.js vue-props vuejs3

我拼命尝试watchpropVue3(3.2.31,Composition API)中:

\n
<script lang="ts" setup>\nimport { toRef, watch } from \'vue\'\n\nconst props = defineProps({\n  \'trigger-refresh\': {\n    type: String\n  }\n})\nconst triggerRefresh = toRef(props, \'trigger-refresh\')\nwatch(triggerRefresh, (a, b) => console.log(\'props triggered refresh\'))\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n

我触发了 的发射trigger-refresh,它通过上面的代码传递给组件,并且我看到triggerRefreshDevTools\xe2\x86\x92Vue 中发生了变化

\n

watch因此,除了未触发(即控制台上没有消息)之外,组件内部的一切都很好。

\n

我阅读了Watchers 的文档以及对有关观看道具的问题的答复(其中一个答复几乎与我所做的相同),但我只是无法理解为什么这在我的情况下不起作用。

\n

Bou*_*him 8

尝试添加immediate选项以便在第一次道具更改时触发手表:

watch(triggerRefresh, (a, b) => console.log('props triggered refresh'), {
  immediate: true
})
Run Code Online (Sandbox Code Playgroud)