Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional @click with a method in vuejs

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?

like image 954
alikhar2018 Avatar asked Dec 12 '18 11:12

alikhar2018


People also ask

What is the difference between V-if and V show?

The key difference is that v-if conditionally renders elements and v-show conditionally displayselements. This means that v-if will actually destroy and recreate elements when the conditional is toggled. Meanwhile, v-show will always keep the element in the DOM and will only toggle its display by changing its CSS.

Does V-if destroy component?

v-if is "real" conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.

What is V-if in VUE JS?

The v-if directive is a Vue. js directive used to toggle the display CSS property of a element with a condition. If the condition is true it will make it visible else it will make it invisible.

How do I apply conditional condition in Vue?

In VueJs, we can simply write a conditional class by binding it, and to do so all we need to do is to use the v-bind:class we can also write it in the short form as :class Both are applicable and will do the same work.


1 Answers

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

like image 159
Jns Avatar answered Oct 11 '22 10:10

Jns