Vue loop binding event listener only binds with the first few elements.

Spread the love

I faced a problem when I had to attach an event listener to many elements rendered through the loop. When rendered, the click event was only attached to the first element and all the other elements didn’t have the listener attached. So, I solved this by passing an additional argument to the listener which was different for each element. It seems like the other library which I was using, returning the same reference at the time of rendering, and Vue was not attaching the listener based on the same reference.

Below was code before:

<wj-flex-grid-column
                :binding="c.binding"
                :header="c.header"
                :isReadOnly="true"
                :stickyHeaders="false"
                v-for="(c, index) in gridColumns()"
                :key="index"
                :width="c.width"
                :maxWidth="c.width"
                :minWidth="c.width"
                :align="c.align"
            >
                <wj-flex-grid-cell-template cellType="Cell" v-slot="cell" :class="getCellClass(c)">
                    <div :class="getCellInnerClass(cell)" @click="onCellClick(cell)">
                        <span v-if='cell.col.binding === "name"' :title="cell.item.name">{{cell.item.name}}</span>
                        <span v-if='cell.col.binding !== "name"'> {{" "}} </span>
                    </div>
                </wj-flex-grid-cell-template>
            </wj-flex-grid-column>

After:

<wj-flex-grid-column
                :binding="c.binding"
                :header="c.header"
                :isReadOnly="true"
                :stickyHeaders="false"
                v-for="(c, index) in gridColumns()"
                :key="index"
                :width="c.width"
                :maxWidth="c.width"
                :minWidth="c.width"
                :align="c.align"
            >
                <wj-flex-grid-cell-template cellType="Cell" v-slot="cell" :class="getCellClass(c)">
                    <div :class="getCellInnerClass(cell)" @click="onCellClick(cell, c.binding)">
                        <span v-if='cell.col.binding === "name"' :title="cell.item.name">{{cell.item.name}}</span>
                        <span v-if='cell.col.binding !== "name"'> {{" "}} </span>
                    </div>
                </wj-flex-grid-cell-template>
            </wj-flex-grid-column>

There is only one difference: In ‘onCellClick’ function I have passed an argument which is different for each render, that solved the problem of non attachment of event.

If you have a better explanation, then please comment.

Cheers and Peace out!!!