2

I have a template with several divs, each containing an @click that triggers a specific function and a corresponding visual effect

<template>
    <div @click="function doThis(param1)></div>
    <div @click="function doThis(param2)></div>
    <div @click="function doThis(param3)></div>
    <div @click="function doThis(param4)></div>
    <div @click="function doThis(param5)></div>
</template>

method: {
    doThis(param) {
        lightUpDiv(corresponding param)
    }
}

I'm also calling doThis from the parent via a $broadcast. What if any, is the best Vueish way to trigger the corresponding lightUpDiv call from the $broadcast? (just use getElementById and .click()???). I used individual divs vs a v-for in the hope that this is easier.

I should note that there are several instances of the template On the page. Even if the same visual effect is caused simultaneously on all the templates that is fine. If there is a way to call them on the specific template instances that is even better.

I've spent hours trying to figure this out and cannot seem to do it. Have read all the guide and API. I know there is some way to bind the data to make the template instances unique but can't seem to get it. Definitely couldn't see the @click from $broadcast solution

Thanks for any help!!

1 Answer 1

2
  • <div @click="doThis"></div>

OR

  • <div @click="doThis($event)"></div>

Both are functionally equivalent, but second version is recommended as it is more explicit.

In javascript,

doThis: function(ev){
  //ev is event object and ev.target refers to the div you need.
  alert(ev.target.innerHTML);

}  

Demo

Event object details

Sign up to request clarification or add additional context in comments.

3 Comments

Raj, thank you for this! However still unsure how I would call the doThis function and activate the corresponding div. ev.target only gets me the target triggered through the @click, no? Per your demo I would still be unable to call doThis(Is) and have it trigger the alert? Apologies if I'm missing something. Thank you.
define doThis as function( ev, para) and pass argument as doThis($event, ' a random para'). Now para will correspond to whatever you passed as second argument. if you call doThis($event, abc) then para will refer to this.abc
Raj, thank you for clarifying. That makes sense. I will have to play around with it a bit. Thanks for the help!

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.