Dickson Afful
Dickson Afful

Reputation: 838

How to create input fields dynamicaly in vuejs (vuetify)

I am new to vuejs. I'd wanted to create input fields dynamically by the click of a button using vuetify. My attempt to implement is shown below and commented line wise to show what I was trying to achieve. I there a way this can be done? Any suggestion is welcome.

<template>
    <v-container>
        <v-row>
            <v-col cols="12" sm="12">
                <v-btn color="success">Add Input</v-btn>
            </v-col>
            <v-col cols="12" sm="12" ref="mount">
                <!-- inputs fields are appended here -->
            </v-col>
        </v-row>
    </v-container>
</template>

<script>
    export default {
        data() {
            return {
                items: {},
            };
        },
        methods: {
            addField() {
                // create element
                let textField = document.createElement("v-text-field");
                // add it to the data property
                this.$data.items["firstName"] = "";
                // add the vmodel attribute to the element
                textField.setAttribute("v-model", "firstName");
                // finally mount it in the templates
                this.$refs.mount.appendChild(textField);
            },
        },
    };
</script>


Upvotes: 2

Views: 1439

Answers (1)

Reinier68
Reinier68

Reputation: 3242

You should use an array of objects like so basic: [{ name: "", time: "" }]. Then you can use a loop to bind inputfields to those properties and add items to that array. You can see a working example here

<div v-for="item in basic" :key="item.id">
    <button @click="addRow">Add row</button>
    <input type="text" v-model="item.name" />
    <input type="text" v-model="item.time" />
    {{ item.name }} - {{ item.time }}
</div>
data () {
    return {
        id: 1,
        basic: [{ name: "", time: "" }]
    };
}
addRow () {
    console.log("added");

    this.id += 1;
    this.basic.push({
        name: "",
        time: ""
    });
}

Upvotes: 3

Related Questions