Home > Enterprise >  Vue3 - Set HTML Attribute as a prop in subcomponent
Vue3 - Set HTML Attribute as a prop in subcomponent

Time:10-05

How can I pass the prop type over to the HTML attribute "type" found in the input tag?

When running this code in the browser, the password input is still working like a standard text input.

    <div >
        <Card>
          <form>
            <Input label="Username" type="text"/>
            <Input label="Password" type="password"/>
          </form>
        </Card>
    </div>

Input.vue

<script lang="ts">

    export default {
        props: {
            label: String,
            type: String,
        },
    }

</script>

<template>
    <div >
        <label  for={{label}}>
            {{label}}
        </label>
        <input  id={{label}} type={{type}}/>
    </div>
</template>

Thanks for any help.

CodePudding user response:

The syntax you are using to bind the html attributes to your props is wrong: the double curly brackets {{ }} can be used only to add text inside the content of a tag. Instead you should bind reactive values to HTML properties in the following way: <tag :propertyName="propertyVariable"></tag>. In your case, for example:

    <template>
        <div >
            <label  :for="label">
                {{label}}
            </label>
            <input  :id="label" :type="type"/>
        </div>
    </template>

You can find a complete explanation here.

  • Related