Home > other >  Vue how to add click event to <nuxt-img>
Vue how to add click event to <nuxt-img>

Time:11-30

In my vue-app I need to make a <nuxt-img />-clickable, so I tried to do this:

<nuxt-img :src="image.src" @click="isClickable ? doSomeStuff : null" />

but for some reason I don't know, this is not working - nothing happens on click.

Can someone tell me what I'm doing wrong?

CodePudding user response:

Try to add the native modifier :

@click.native="isClickable ? doSomeStuff : null"

CodePudding user response:

I would pass a function there, like somebody already suggested in the comments:

@click="() => isClickable ? doSomeStuff : null"

but better would be to enclose the logic in a method and call the method @click="handleClick"

...
methods: {
  handleClick(){
    if(this.isClickable){ this.doSomeStuff() }
}

CodePudding user response:

<nuxt-img :src="image.src" @click="isClickable ? doSomeStuff : null" />

doSomeStuff has to be defined as a function in order to be called like that

Otherwise you should call it with a thunk

For instance:

<nuxt-img :src="image.src" @click="isClickable ? () => doSomeStuff : null" />

Still I would give an undefined to the @onclick event instead of a null value

<nuxt-img :src="image.src" @click="isClickable ? () => doSomeStuff : undefined" />
  • Related