0

I have created in my vue component the following template

                <b-button v-on:click="check($event)" class="btn btn-success" data-action="consent">
                    <b-icon-check></b-icon-check>
                </b-button>

However the click event only seems to work if I click on the button itself, for example on the sides around the icon, and not when clicking on the icon itself.

I'm wondering if there's a better way to do what I want to achieve instead of adding another v-on:click on the icon itself.

Basically I want the button to trigger the click event even if any subelement it has is clicked.

enter image description here

Here's the function check(event)

    methods:{
        check(event){
            let action = event.target.getAttribute('data-action');
            if(action === 'consent'){
                this.checked = true;
            }
            else{
                this.checked = false;
            }
        }
    },

After reading the comments and the link for modifiers, I think my mistake is assuming that the event.target is going to be the button. Instead it's the icon itself that's why my code is failing.

gabtzi
  • 573
  • 3
  • 8
  • 24
  • It looks like something is stopping the icon from bubbling to the button, can you share the code of the `check` method? – dako Mar 20 '20 at 10:01
  • Test the modifiers of v-on: https://vuejs.org/v2/guide/events.html#Event-Modifiers – menepet Mar 20 '20 at 10:03
  • I just updated the question because I think the event is actually triggering but doesn't work because I'm working on the wrong event.target. But I'm wondering why it doesn't propagate to the button as well. – gabtzi Mar 20 '20 at 10:11
  • I've tested your code, and it did trigger the event when click on the icon – Lay Mar 20 '20 at 10:14
  • you missed `data-action` for the icon which fails `event.target.getAttribute('data-action')` add `data-action="consent"` to the `` – PRAJIN PRAKASH Mar 20 '20 at 10:17
  • Wouldn't it be simpler to rewrite it to `@click="check('consent')"`, so you don't need the event target to get the `data-action` attribute? – Hiws Mar 20 '20 at 10:21
  • True that would be much simpler, but I need the target as well to add some classes to it later on for styling purposes on each case. – gabtzi Mar 20 '20 at 10:25

1 Answers1

3

Use event.currentTarget.getAttribute('data-action') to grab the data* attribute from where the event listener is bound. event.currentTarget will always be the element the event listener is bound to (rather than the element that actually initiated the click event, which is what event.target points to).

Troy Morehouse
  • 5,320
  • 1
  • 27
  • 38