Conditional @click with a method in vuejs

折月煮酒 提交于 2020-06-12 07:23:26

问题


This is my for loop:

  <li v-for="(crumb, index) in breadcrumbs" :class="{ 'is-active' : index==breadcrumbs.length-1 }">
    <a href="javascript:void(0)" v-if="index==breadcrumbs.length-1">{{ crumb.name }}</a>
  </li>

@click="methodName" shouldn't be available for the last iteration.

I can check the last iteration with index==breadcrumbs.length-1 Is this possible using apply v-if?


回答1:


There is a possibility by defining the event handler this way:

v-on="condition ? { eventName: () => handler } : {}"

The ?: operator can be used as a shortcut for an if...else statement

In your case it would be like this:

<li v-for="(crumb, index) in breadcrumbs" :class="{ 'is-active' : index==breadcrumbs.length-1 }">
    <a href="javascript:void(0)" v-on="index < breadcrumbs.length-1 ? { click: () => methodName(parms) } : {click: ($event) => $event.preventDefault() }" >{{ crumb.name }}</a>
</li>

Small fiddle



来源:https://stackoverflow.com/questions/53742525/conditional-click-with-a-method-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!