Home > Mobile >  Input placeholder value inexplicably moves to its parent element
Input placeholder value inexplicably moves to its parent element

Time:10-09

I'm currently learning Vue3 and have run into a strange issue I can't seem to find a solution for.

I have this simple CoordinateField component, which is essentially just a text input field. I pass the id and placeholder values in as props. However, in the output, for some reason the placeholder value moves from the input field to its parent div element, thus obviously not showing up in the field. I've also tried wrapping placeholder in [[ ]] but that didn't help.

Here is my code and an example:

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

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

The component is called inside other components simply like this:

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

A screenshot of the output

CodePudding user response:

This is happening because you have defined the prop placeholderText but using attribute placeholder. As this attribute are not recognized as prop it inherit as attribute.

To prevent attribute inheritance you can use inheritAttrs: false and bind attributes to target elements using v-bind="$attrs"

<template>
    <div class="text-field">
        <input type="text" class="text-field__input" v-bind="$attrs" />
        <label :for="id" class="text-field__label"></label>
    </div>
</template>

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

More about non-prop attributes: https://v3.vuejs.org/guide/component-attrs.html#attribute-inheritance

  • Related