Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a method from created hook in vuejs component

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?

like image 386
epeleg Avatar asked Apr 17 '18 07:04

epeleg


2 Answers

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');
  },
  ...
}
like image 50
Marco Pantaleoni Avatar answered Sep 29 '22 08:09

Marco Pantaleoni


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.

like image 28
Sumit Parkash Avatar answered Sep 29 '22 07:09

Sumit Parkash