Home > other >  How do I get default props in custom input field in vue3?
How do I get default props in custom input field in vue3?

Time:11-01

I want to make custom input component of default input like this.

<template>
  <input  type="text"> 
</template>

<script>
export default {
  name: "CustomInput",
}
</script>

How can I add all prop which is default of automatically without define. example if I set placeholder on CustomInput then this placeholder automatically apply on input Where I doesn't need to write placeholder as prop in component CustomInput.

<CustomInput placeholder="test"/>
//it will be apply like 
<input placeholder="test"/>

CodePudding user response:

By default, a component's root element automatically inherits attributes applied to the parent, so the behavior you're seeking already occurs. For attribute inheritance to work, there can only be a single root element. Even an adjacent comment element will disable the inheritance.

<!-- input inherits attributes -->
<template>
  <input /> 
</template>

<!-- No attribute inheritance -->
<template>
  <!-- my comment -->
  <input />
</template>

<!-- No attribute inheritance -->
<template>
  <label for="password">Password</label>
  <input id="password" type="password" ​/><p>Enter a unique password</p>
</template>

When you can't rely on attribute inheritance (e.g., multiple root elements exist, or the target is nested within other elements), you can disable the attribute inheritance with the inheritAttrs=false option, and use v-bind="$attrs" on the target element:

<template>
  <label for="password">Password</label>
  <input id="password" type="password" v-bind="$attrs" ​/><p>Enter a unique password</p>
</template>

<script>
export default {
  inheritAttrs: false,
}
</script>

Also note that v-model doesn't automatically work for components, even when an <input> is the single root element. The component must explicitly implement the v-model interface (i.e., receive a modelValue prop, and emit the update:modelValue event):

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

<script>
export default {
  name: 'CustomInput',
  props: ['modelValue'],
}
</script>

demo

  • Related