multiple forms with the same Vue model instance, on click always getting first form data

Viewed 391

I need to have separated choice options with the button for every one. When I click on the button of any of them I'm getting data for first one. why I am always get the data from first form? How to get data of the form that button was clicked?

here I have some piece of code, hope it will help

HTML

    <div v-for="p in items">
        <form>
            <input type="radio" name="p" v-model="selectedP" :value="p.pk" :id="'p-' + p.pk" :checked="'checked'">
            <label :for="'p-' + p.pk" class="cmn-p__inner">
                <div>
                    <img :data-src="p.image.url" :alt="p.image.alt">
                </div>
                <p>{p.title}</p>
            </label>
            <div>
                <button @click.prevent="saveP()" type="submit">Choose</button>
            </div>
        </form>
    </div>

Vue

    var app = new Vue({
        el: '.js-order-detail',
        delimiters: ['{', '}'],
        filters: {
            priceFormat: function(value) {
                if (value) return window.formatMoney(value, 2);
                return value;
            }
        },
        data: {
            ..................
            selectedP: null,
            
            ..................

        methods: {
            saveP: function(url) {
                var self = this;
                var data = {
                    p: self.selectedP
                };

                $.ajax({
                    url: self.url,
                    type: 'post',
                    data: data,
                    success: function(response) {
                        window.alert(
                            null,
                            null,
                            '#p-success-add',
                            3000
                        );
                    },
                    error: function() {
                    },
                    complete: function() {
                    }
                });
            },
        }
1 Answers

I have answer for my question, may be its wrong way for this kind of tasks/for Vue.js, but this is the way I did it:

in Html I move all data to the button:

    <button @click.prevent="saveP()" type="submit" name="p" v-model="selectedP" :value="p.pk" :id="'p-' + p.pk">Choose</button>

in Vue code, I have changed the data in the method saveP:

    methods: {
        saveP: function(url) {
            var self = this;
            var data = {
                present: event.target.value
            };
               .....................

if anybody know more correct way for this task or reason why this is not good way to do, please left your comments or answer.

Related