You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 自定义CoordinateField组件placeholder值莫名转移至父元素问题求解

问题原因

你的问题是由Vue3的非Prop属性透传特性导致的:

  • 你在组件中定义的props为placeholderText,但外部调用组件时传入的属性名是placeholder
  • 由于placeholder没有被声明为组件的props,Vue会默认将这个未被识别的属性直接挂载到组件的根节点(也就是你组件里的<div class="text-field">)上,所以才会出现placeholder跑到父级div的情况

解决方案

方案1:统一属性命名(最推荐)

直接将组件内的props名改为placeholder,和调用时的传参名对齐即可:

<template>
    <div class="text-field">
        <input type="text" :id="id" class="text-field__input" :placeholder="placeholder" />
        <label :for="id" class="text-field__label"></label>
    </div>
</template>

<script>
export default {
    props: {
        id: {
            type: String,
            required: true
        },
        placeholder: {
            type: String,
            required: true
        }
    }
}
</script>

调用方式不用改动,保持现有写法即可正常生效。

方案2:调用时对齐组件现有props名

如果不想改组件内部代码,也可以在调用组件时把属性名改为组件内声明的placeholderText:

<CoordinateField id="lat" placeholderText="Latitude" />
<CoordinateField id="lng" placeholderText="Longitude" />

补充:关闭自动透传(特殊场景需要)

如果你后续有需求不想让未声明的属性自动挂载到根节点,可以在组件选项中添加inheritAttrs: false,之后如果需要把属性绑定到指定元素,可以通过$attrs手动绑定:

<script>
export default {
    inheritAttrs: false, // 关闭自动透传
    props: {
        // 原有props配置不变
    }
}
</script>

内容的提问来源于stack exchange,提问作者Scopuli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:24:03