首页 > 解决方案 > 如何将事件处理程序添加到 Vue 循环中的第一项?

问题描述

我有一个正在迭代的项目列表,需要以编程方式将事件处理程序添加到第一个呈现的元素。我看不出这在 Vue 中是如何实现的。

<div ref="componentList" class="component-list col-9">
            <template
                v-for="( course, index ) in sortedCourseList"
            >
                <span
                    v-if="( index > 0 ) && (course.courseTitle[ 0 ] !== sortedCourseList[ index - 1].courseTitle[ 0 ])"
                    :id="course.courseTitle[ 0 ]"
                    :key="index"
                    class="component-list__letter-heading"
                >
                    {{ course.courseTitle[ 0 ] }}
                </span>
                <CardLong
                    v-else
                    :key="index"
                    :ref="'card' + index"
                    >>> EVENT HANDLER <<<
                    :title="{
                        text: course.courseTitle,
                        order: 1,
                    }"
                    titleTag="h2"
                    icon
                />
            </template>
        </div>

我正在寻找在哪里实施类似的东西

if ( index === 0 ) { ... }

在 CardLong 组件实例中。

标签: loopsvue.jsvuejs2

解决方案


您可以使用三元运算符有条件地在您的事件上调用函数,无论是什么:

<div v-for="(a, i) in [1,2,3,4]" :key="i" @click="i == 0 ? doSomething() : ''">
  Click Me!
</div>

推荐阅读