Call methods of the same component with Vue

1.3k views Asked by At

I have a vue component with 2 methods, deleteActivitat calls an axios.get method and then, this calls the other vue method reloadActivitats:

methods: {
  reloadActivitats: function () {
    this.$store.dispatch(actionTypes.FETCH_ACTIVITATS)
  },
  deleteActivitat: (activitat) => {
    crud.delete(activitat).then((response) => {
      this.reloadActivitats() // calls reloadActivitats method
    }).catch((error) => {
      console.log(error);
    });
  }
}

But when I run the application the reloadActivitats method is not executed and the console shows the next error:

TypeError: _this.reloadActivitats is not a function

Image with the vue error

Any idea of what I'm doing wrong?

3

There are 3 answers

0
Agney On BEST ANSWER

Instead of using an arrow function, you need to change the usage to a function

deleteActivitat: function(activitat) {
  crud.delete(activitat).then((response) => {
    this.reloadActivitats() // calls reloadActivitats method
  }).catch((error) => {
    console.log(error);
  });
}

This is because arrow functions do not bind the value of this. this has to be bound to the vue instance for this.functionName() to work.

You can also use deleteActivitat() syntax as described here.

0
Rentonie On

Don't use arrow function for the deleteActivitat.

The arrow function is bound to the parent context, and not the Vue instance.

Try

deleteActivitat: function (activitat) {

demo: https://codesandbox.io/s/vnm40qkzz5?expanddevtools=1&module=%2FApp.vue (Open the console)

0
tolotra On

Avoid to use arrow functions in methods object member.

deleteActivitat (activitat) {
    crud.delete(activitat).then((response) => {
      this.reloadActivitats() // calls reloadActivitats method
    }).catch((error) => {
      console.log(error);
    });
  }