alikhar2018
alikhar2018

Reputation: 145

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?

Upvotes: 11

Views: 17161

Answers (3)

Majali
Majali

Reputation: 531

Just another way to handle conditional @click, especially if we have multiple cases

We call the method

v-on="myMethod(breadcrumbs.length, index)"

and inside the method we do handle the conditional

myMethod(let length, let index){
  if (index == 0){
    this.myMethod1()
  } 
else if (index == length-1){
  this.myMethod2()
}

Upvotes: 0

Świeżu
Świeżu

Reputation: 195

@click="someBooleanVariable ? console.log('yes') : {}"

Upvotes: 1

Jns
Jns

Reputation: 3257

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

Upvotes: 39

Related Questions