invoke different onClick functions in a v-for loop

Viewed 366

I have a set of data that needs to be looped through but each item in that data has a different onClick event. Something along the lines like:

list: [
  {
    text: 'a',
    icon: 'a-icon',
    onClick: () => {
      // do stuff a
    },
  },
  {
    text: '`b`',
    icon: 'b-icon',
    onClick: () => {
      // do stuff b
    },
  },
]

what I initially tried to do was:

<div v-for="(item, i) in list" :key="i" @click="item.onClick()"></div>

which didn't work. The error was:

TypeError: item.onClick is not a function

Then I tried:

<div v-for="(item, i) in list" :key="i" @click="list[i].onClick()"></div>

which looks weird but works. Only I can't access this inside onClick function. I could just pass this to the function directly like @click="list[i].onClick(this)" but it look weird too.

I knonw I can write a method and do switch according to the index. But then I had to write the onClick function seperately.

Is there a better way to do this?

1 Answers

const app = new Vue({
  el: "#app",
  data() {
    return {
      list: [{
          text: 'a',
          icon: 'a-icon',
          onClick: (item) => {
            let element = document.getElementById(item.text);
            console.log(element);
            console.log("Item" + item);
            console.log("Hi")
          },
        },
        {
          text: '`b`',
          icon: 'b-icon',
          onClick: (item) => {
            console.log("Item" + item);
            console.log("Hello")
          },
        },
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(item, i) in list" :key="i" :id="item.text" @click="item.onClick(item)">{{item.text}}</div>
</div>

It's depends on what you mean by this. Is this the HTML element you are working with, or the array element being looped.

<div v-for="(item, i) in list" :key="i" @click="item.onClick(item)"></div> //If `this` refers to the array element being looped

If this refers to the HTML element in that loop: You can assign an unique id, probably :id="'item_list'+id" then pass it as method parameter live above. Then select the element within the method. There's defintely a better way but till now that's what I can think of

And in addition, since you are using arrow function, it may point to its nearest parent that have this. Try using anonymous function if it suits your need.

Related