jj008
jj008

Reputation: 1083

Error: not a function (on mounted)

I'm trying to implement something to close all menus/modals when a user clicks outside of the menu/modal area.

this.closeMenu() is being invoked correctly but I'm getting an error that says this.closeMenu is not a function. What's the reason for this?

methods: Object.assign({},
  {
    closeMenu(){
      console.log("close menu")
    }
  }
)


mounted(){
  $(document).on('click', function(event) {
    if (!$(event.target).closest('.menu').length){
      // close all menus
      this.closeMenu()
    }
  });
}

Upvotes: 0

Views: 559

Answers (1)

ittus
ittus

Reputation: 22403

this keyword here is not Vue instance. You can do a trick by assign var self = this

mounted(){
  var self = this;
  $(document).on('click', function(event) {
    if (!$(event.target).closest('.menu').length){
      // close all menus
      self.closeMenu()
    }
  });
}

Upvotes: 1

Related Questions