An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
Sending a V-Model Through a Slot in Vue 3
If you ever attempt to send a v-model
through a slot in Vue 3 (or Vue 2), you learn pretty quickly that it isn't possible out of the box. However, there is a workaround.
The following code example allows you to update the internal state of the SlottedComponent from a parent. This is useful in cases where you want the consumer of your component to be able to style or control its internal state.
SlottedComponent:
<template> <slot :input-value="inputValue" :update-input-value="updateInputValue" /></template><script lang="ts" setup> const inputValue = ref('') const updateInputValue = (event: Event) => { inputValue.value = (event.target as HTMLInputElement).value }</script>
In a parent component:
<template> <SlottedComponent> <template #default="{ inputValue, updateInputValue }"> <input type="text" :model-value="inputValue" @keyup="updateInputValue" > </template> </SlottedComponent></template>
The key here is that you cannot listen to the @update:model-value
event as you typically would for a v-model
since that event cannot cross the slot boundary. But, you can call an event, such as @keyup
and send the value of the input element back to the SlottedComponent.
I hope you found this useful. Have a great day.
Original Link: https://dev.to/jshimkoski/sending-a-vue-3-v-model-through-a-slot-2g43
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To