【问题标题】:How do I get default props in custom input field in vue3?如何在 vue3 的自定义输入字段中获取默认道具?
【发布时间】:2021-12-15 06:06:00
【问题描述】:

我想像这样制作默认输入的自定义输入组件。

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

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

我怎样才能添加所有默认的道具,没有定义。例如,如果我在 CustomInput 上设置占位符,则此占位符会自动应用于 input 我不需要在组件 CustomInput 中将占位符写为道具。

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

【问题讨论】:

    标签: vue.js vue-component vuejs3


    【解决方案1】:

    默认情况下,组件的 根元素 会自动将inherits attributes 应用于父级,因此您正在寻找的行为已经发生。要使属性继承起作用,只能有一个根元素。即使是相邻的注释元素也会禁用继承。

    <!-- 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>
    

    当你不能依赖属性继承时(例如,存在多个根元素,或者目标嵌套在其他元素中),你可以disable the attribute inheritance加上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 不会自动对组件起作用,即使&lt;input&gt; 是单个根元素也是如此。组件必须显式实现v-model 接口(即接收modelValue 属性,并发出update:modelValue 事件):

    <template>
      <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
    </template>
    
    <script>
    export default {
      name: 'CustomInput',
      props: ['modelValue'],
    }
    </script>
    

    demo

    【讨论】:

    • tony19 有没有办法继承指令??
    • 不,我认为这不可能。您必须更新指令本身才能在需要的地方访问组件。
    • 好的,非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-06-29
    • 2021-01-06
    • 2018-07-15
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多