Search code examples
vue.jsv-for

v-for in vue 2 could not pass values dynamically to @change function


In vue2, I have used v-for on a div and there is a button with a function in that div. passing values to that function are not dynamic.

Have a look on my code. I am working in vue2.

<div class="revision-row completed-revision" v-for="(revision, index) in singleOrder.revisions" :key="index">
    <div class="reveision-button" :data-rvv="revision.id" v-if="revision.status == 'Payment Done'">
        <div class="revision-payment-btn">
            
            <input class="white-field" style="display:none" multiple accept="image/*,video/*"
                   @change="submitRevision(singleOrder.id,revision.id,index,$event)" type="file" name="fileinputnew"
                   id="revisionImage">
            <label for="revisionImage" class="imgs-uploaderss">
                Submit Drawing
            </label>
        </div>
    </div>
</div>

submitRevision(a,b,c,c){ alert(a) }

alert always prints the first one div's singleOrder.id value and could not change dynamically for each.


Solution

  • It happens because you use the same ID on the different html elements. It is not recommended. Discussion about ID.

    Solution:
    :id="`revisionImage${revision.id}`"
    :for="`revisionImage${revision.id}`"

    Be sure that revision.ids are unique

    Try this:

    <div class="revision-row completed-revision" v-for="(revision, index) in singleOrder.revisions" :key="index">
        <div class="reveision-button" :data-rvv="revision.id" v-if="revision.status == 'Payment Done'">
            <div class="revision-payment-btn">
                
                <input class="white-field" style="display:none" multiple accept="image/*,video/*"
                       @change="submitRevision(singleOrder.id,revision.id,index,$event)" type="file" name="fileinputnew"
                       :id="`revisionImage${revision.id}`">
                <label :for="`revisionImage${revision.id}`" class="imgs-uploaderss">
                    Submit Drawing
                </label>
            </div>
        </div>
    </div>```