Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 16, 2022 01:16 pm GMT

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To