I encountered an issue with Vue3's watch
or onUpdated
:
Although I can successfully trigger the callback using both, there is a particular scenario that poses a problem:
- A user clicks on the Delete button and sets the
targetId
tosomeId
- The
<Modal/>
'swatch
is triggered as theprops.id
changes, displaying a bootstrap Modal - If the user accidentally clicks outside the modal and hides it
- When the user tries clicking the Delete button again, even though the
targetId
is still set tosomeId
, the<Modal/>
'swatch
does not trigger. As a result, the modal does not reappear
As seen in my code snippet, I attempted to reset targetId
to 0 every time showModal
was called, but this did not resolve the issue. It seems that although targetId
did change twice, it is not being "watched" by the <Modal/>
Essentially, my goal is to trigger the watch
or onUpdated
even when the old value equals the new value (I understand this may not be directly possible). Thus, I tried setting it to a default value and then changing it back, hoping to provoke two changes ("oldVal -> 0" and "0 -> oldVal"), but this approach also did not work.
<!-- Parent -->
<template>
<button @onclick="showDeleteModal(someId)">Delete</buton>
<Modal :id="targetId"/>
</template>
<script setup>
const targetId = ref(0)
const showDeleteModal = (id)=>{
<!-- Changing to 0 then back to id does not work -->
targetId.value = 0
targetId.value = id
}
</script>
<!-- Child(Modal) -->
<template>
some template
</template>
<script setup>
const props = defineProps({id: Number})
watch(()=>props.id, ()=>{
<!-- Show the Modal here -->
})
</script>