1

I'm v-for some buttons from some data, these data contain callback that I want to bind to <button />.

I know some of those data have no callback, so I wrote this

<button @click="item.click || (() => {})"></button>

However, this line is not working as I expected, now, all my buttons' click event is not doing things anymore.

Please see this minimum example

<template>
  <div>
    <div v-for="(item, itemIndex) in data" :key="itemIndex">
      <button @click="item.click || (() => {})">Click {{ itemIndex }}</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: [
        {
          click: () => {
            alert("First Item");
          },
        },
        {
          // Empty Object
        },
      ],
    };
  },
};
</script>

What should I do to prevent empty callbacks?

Here is my CodeSandbox

enter image description here

(Click 0 is not working)

1 Answer 1

2

You should do this in the click listener:

@click="item.click ? item.click() : (() => {})"

instead of

@click="item.click || (() => {})"
Sign up to request clarification or add additional context in comments.

3 Comments

Doesn't item.click() tries to execute click function instead of just passing function reference to @click?
@JosephWang you are welcome, please mark the answer as the solution if it solved your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.