n_osennij
4 months ago
157
5
Vue

Dynamic v-model

Posted 4 months ago by n_osennij

I have dynamic form (the number of fields is variable and has different names; for example temperatyra and time). So, to submit form I need first save this data to variable. But how can I create dynamic v-model variables? I try next

<div v-for="specification in journal.specifications" :key="specification.id">
    <input type="text" :id="specification.slug" :name="specification.slug" v-model="form[specification.slug]>
</div>

But if look at VueDevtools or send form to server - its empty. If console.log(this.form) result will be next

[temperatyra: (...), vlagnost: (...), time: (...), __ob__: Observer]
temperatyra: (...)
time: (...)
vlagnost: (...)
length: 0

Pay attention to length: 0

What can I do?

all component code

<template>
    <form action="#" method="POST" @submit.prevent="setEntry">
        <div class="form-group" v-for="specification in journal.specifications" :key="specification.id">
            <label :for="specification.slug">{{specification.name}}</label>
            <input type="text" class="form-control" :id="specification.slug" :name="specification.slug" v-model="form[specification.slug]" required>
        </div>
        <button type="submit" class="btn btn-primary btn-block">Submit</button>
    </form>
</template>

<script>
    export default {
        name: "JournalComponent",
        props: [
            'journal_id',
        ],
        mounted() {
            this.getJournalData();
        },
        data() {
            return {
                journal: [],
                form: [],
            }
        },
        methods: {
            async getJournalData() {
                let response = await axios.get('/journals/specifications/' + this.journal_id);
                this.journal = response.data;
            },
            async setEntry() {
                console.log(this.form);
                let response = await axios.post('/entries', {
                    form_data: this.form,
                });
            }
        }
    }
</script>

Please sign in or create an account to participate in this conversation.