Search code examples
vue.jsaddeventlistenereventtrigger

How to bind a click event to a button when component is mounted vue js?


I am using a third party app (vue slick carousel) and I need to bind a click event to below button

<button type="button" data-role="none" class="slick-arrow slick-next" style="display: block;">
    <svg...</svg>
</button>

So everytime I click this button a function gets triggered. This is what I tried in mounted and created life cycle, but didn't bind click event to it.

// console.log(document.querySelector(".slick-next")); // this returns element stated above

document.querySelector(".slick-next").addEventListener("click", () => {
  console.log("Works");
});

I tried using setAttribute hoped it works, but it didn't work either.

Any help is appreciated. Thank you in advance.


Solution

  • I suspect they're probably using stopPropagation on the button click inside the component then.

    There might be another way around this depending on your needs:

    <VueSlickCarousel @beforeChange="checkChange">
        ...
    </VueSlickCarousel>
    

    methods: {
        checkChange(oldSlideIndex, newSlideIndex) {
            if (newSlideIndex > oldSlideIndex) {
                console.log("Next button clicked");
            }
        }
    }
    

    Another option might be to use the <template #nextArrow="{ currentSlide, slideCount }"></template> slot inside the Carousel tag and use your own button. You'd probably have to implement your own logic for setting the next slide if you went this route.