Skip to content
Advertisement

What is the best way to reference an item in Vue?

My goal is to get the item that was clicked and based on that do some action.

I have a few items that share the same event (click) but have different functionality. I want to unite them under one function and based on some attribute refer to the clicked item.

So far I’ve been doing this using classes, for instance

onClick(event) {
      let classList = event.currentTarget.classList;
      switch (true) {
        case classList.contains('first-class'):
          //do this;
          break;
        case classList.contains('second-class'):
          //do that;
          break;
      }
  },

But I feel that it is not the best way cause classes might change in the future due to different reasons and then this code will fail.

Is there any other way to refer to an item on click?

Advertisement

Answer

When you click on an object, you can pass a parameter, you are not stuck with event :

<i @click="onClick('variableA')" />
<i @click="onClick('variableB')" />

And then :

onClick(variable) {
      if (variable === 'variableA') {
         ...
      }
  },
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement