Search code examples
javascriptvue.jsmaterializevuejs3

How to access vue3 methods from event listener callback function


Description

In the mounted() part of the component I add an event listener, which should call one of the methods.

Code

export default {
  methods: {
    changeState: function(el) {console.log(el);}
  },
  mounted() {
    document.addEventListener('DOMContentLoaded', function() {
     
      //I'm using materialize.css carousel here
      //---------------------------------------
      var elems = document.querySelectorAll('.carousel');
      M.Carousel.init(elems, {
        onCycleTo: function(el) {
          this.changeState(1);
         }
      });
    });
  }
}

Problem

I think there are two problems :

  • this in onCycleTo refers to the function in onCycleTo and not to the methods part
  • the eventListener gets added to the document, which is on a different scope, so this.changeState(1) refers to a global function (which does not exist)

Possible Solution

I think it might be possible to somehow address the methods from a global scope, but I don't know how. Any other solutions also welcome.

How can I resolve these Problems?


Solution

  • Assign this to a global variable called vm then use to access the method :

     var vm=this;
      var elems = document.querySelectorAll('.carousel');
          M.Carousel.init(elems, {
            onCycleTo: function(el) {
              vm.changeState(1);
             }
          });
        });
    

    You could also try arrow function :

      var elems = document.querySelectorAll('.carousel');
          M.Carousel.init(elems, {
            onCycleTo: (el)=> {
              this.changeState(1);
             }
          });
        });