Girish BN
Girish BN

Reputation: 91

access methods from the vue current component

Can any one guide or suggest how to resolve this below issue. Use Case: Trying to implement notification component Scenario: I am trying to call a method or change the state of the data on triggering of event in Vue. I have defined the event listener on mounted function and trying to access one of the method.

enter image description here

Basically, the alert within event function is getting triggered, where as alert inside method is not getting triggered, and even any data manipulation is not executing even with in event function.

Where am i missing? is it incorrect to alter state within Event listener? Basically i am trying to implement notification feature which automatically disappear after few seconds

Any help is appreciated.

Thanks, Girish

Upvotes: 0

Views: 176

Answers (2)

ittus
ittus

Reputation: 22403

There is another reason,this inside callback function is not Vue component. You can assign var self = this and use inside the callback, or use arrow function.

mounted: function () {
  var self = this
  EventBus.$on('show', function () {
    self.test()
    self.show = true
  })
},
methods: {
  test () {
    console.log('Inside methods')
  }
}

Upvotes: 1

Hamilton Gabriel
Hamilton Gabriel

Reputation: 365

I believe your problem is the spelling error instead of

method: {}

, use methods: {} Example:

Error.
method: {
test: function () {
alert('Inside Method');
}

correct.
methods: {
test: function () {
alert('inside method);
}
}

I know it does not have much to do with the question, but be careful when using the event bus, it would be as if you had a speaker, and shouted in the middle of a crowd the name of a person. Example: eventbus says Hamilton in the midst of a crowd of 10,000 people. How many Hamiltons can you have in the middle of this crowd? Use something more specific, such as parent-child communication, avoid using the event bus.

Upvotes: 0

Related Questions