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

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

Posted by: admin November 26, 2021 Leave a comment

Questions:

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?

Answers:

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') {
         ...
      }
  },

###

You can pass specific arguments to the onclick handler in following way.
use $event to pass the event as argument.

<template>
<button @click="onClick($event, 'one')">One</button>
<button @click="onClick($event, 'two')">Two</button>
</template>
onClick(event, text) {
  if (text === 'one') console.log('one is clicked');
  if (text === 'two') console.log('two is clicked');
},

###

In Vuejs you’re suppose to call event (such as change, click) from code like this :

In the template :

<button class"..." v-on:click="func2call"> BTN LABEL </button>

In the script :

methods:{
        func2call (e){
            console.log(e.target)
        }
    }

As you can see e will return the event and e.target the target clicked.
From there you can analyse the target and define what to do depending of its class.