I have a component with the following (partial) code:
export default {
methods: {
mymethod: (x) => {alert(x)},
},
created: () => {
this.mymethod('success');
},
and I am getting the following error:
vue.esm.js?efeb:578 [Vue warn]: Error in created hook: "TypeError: Cannot read property 'mymethod' of undefined"
It would seem like the "this" is not being evaluated to the component's vue instance. And Ideas what could case this?
When defining Vue methods, life-cycle methods, computed properties, ... it's better not using arrow functions, because in that way you are overriding the this
pushed by Vue itself. Try this:
export default {
methods: {
mymethod (x) { alert(x) },
},
created () {
this.mymethod('success');
},
...
}
You have used the arrow function in created hook. Try using
created: function {
this.mymethod('success');
},
if you check the vue.js documentation that also clearly states
Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()). Since arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With