我想像這樣制作默認輸入的自定義輸入組件。
<template>
<input type="text">
</template>
<script>
export default {
name: "CustomInput",
}
</script>
如何在沒有定義的情況下自動添加所有默認的道具。例如,如果我在CustomInput上設定占位符,那么這個占位符會自動應用于輸入,我不需要在組件 CustomInput 中撰寫占位符作為道具。
<CustomInput placeholder="test"/>
//it will be apply like
<input placeholder="test"/>
uj5u.com熱心網友回復:
默認情況下,組件的根元素會自動繼承應用于父元素的屬性,因此您所尋求的行為已經發生。要使屬性繼承起作用,只能有一個根元素。即使是相鄰的注釋元素也會禁用繼承。
<!-- 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>
當你不能依靠屬性繼承(例如,多個根元素存在,或目標被嵌套在其它元件內),則可以禁用屬性繼承與inheritAttrs=false選項,并使用v-bind="$attrs"所述目標元件上:
<template>
<div>
<label for="password">Password</label>
<input id="password" type="password" v-bind="$attrs" ?/>
? <p>Enter a unique password</p>
</div>
</template>
<script>
export default {
inheritAttrs: false,
}
</script>
另請注意v-model,即使 an<input>是單個根元素,它也不會自動對組件起作用。組件必須顯式實作v-model介面(即接收一個modelValueprop,并發出update:modelValue事件):
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
</template>
<script>
export default {
name: 'CustomInput',
props: ['modelValue'],
}
</script>
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344828.html
上一篇:多選組件標簽作為編號
下一篇:沒有插值的情節影片
