0

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?

1 Answer 1

1

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);
         }
      });
    });
Sign up to request clarification or add additional context in comments.

Comments

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.