Home > database >  best alternative for <slot/> in <textarea> in [ Vue.js 3 ] component
best alternative for <slot/> in <textarea> in [ Vue.js 3 ] component

Time:01-21

I want create component with textarea and pass data inside that like

<c-textarea> hello world </c-textarea>

but the classic <slot/> tag not work inside of textarea what's simplest and cleanest alternative

<template>
   <textarea><slot/></textarea>
</template>

in Vue.js 3

CodePudding user response:

You should use value & input to bind the content instead of using slot

Here is the updated version of CTextarea component

<template>
  <textarea :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
  </textarea>
</template>

<script>
export default {
  name: 'CTextarea',

  emits: ['update:modelValue'],

  props: {
    modelValue: String,
  },
};
</script>

check this woking demo

CodePudding user response:

You can extract the content of a slot:

<template>
   <textarea>{{ $slots.default ? $slots.default()[0].children : ''}}</textarea>
</template>

Basically, this builds the slot manually, which gives you a VNode element, where children contains the slot content.

I would really try to find another way though, this is coarse, error prone and most likely not what you want to do.

Personally, I would stick to the v-model approach:

// in your component, just pass all non-props attributes to textarea (or pass them manually)
<template>
   <textarea v-bind="$attrs" />
</template>

// use it like
<your-textarea v-model="content"/>
  • Related