I am desperately trying to watch
a prop
in Vue3 (3.2.31, Composition API):
<script lang="ts" setup>
import { toRef, watch } from 'vue'
const props = defineProps({
'trigger-refresh': {
type: String
}
})
const triggerRefresh = toRef(props, 'trigger-refresh')
watch(triggerRefresh, (a, b) => console.log('props triggered refresh'))
</script>
I trigger the emission of trigger-refresh
, it is passed to the component with the code above and I see triggerRefresh
changing in DevTools→Vue.
So everything is fine up to the inside of the component except that the watch
is not triggered (i.e. there is no message on the console).
I read the documentation for Watchers and responses to a question about watching props (one of the responses is almost identical to what I did) but I simply fail to understand why this does not work in my case.
CodePudding user response:
Try to add the immediate
option in order to trigger the watch at the first prop change:
watch(triggerRefresh, (a, b) => console.log('props triggered refresh'), {
immediate: true
})
CodePudding user response:
Prop names are normalized to camel case. As it was stated in the question, it is triggerRefresh
and not trigger-refresh
that is seen updated. So it should be:
const triggerRefresh = toRef(props, 'triggerRefresh')
watch(triggerRefresh, ...)
Or just:
watch(() => props.triggerRefresh, ...)