Home > Back-end >  can't hit vue method from within axios response
can't hit vue method from within axios response

Time:02-05

I can't figure out what's wrong here, but my axios call works properly and my data response comes back as I expect with success.

The issue now is when I try to call another vue method within my response success from axios. If I comment out the method call then it's fine, but if I leave it the console just reads undefined and I don't get the console.log from within my testFunction so it seems like I'm not even hitting it.

What have I done wrong?

var vm = 
new Vue({
  el: "#app",

  methods: {
   axiosFunc() {
    axios({
      method: 'post',
      url: test,
      data: {
        date:'2022-03-02',
      }

    }).then(function (response) {
      console.log('success');
      this.testFunction();

    }).catch(function (error) {
     
    });
   },
   testFunction() {
     console.log('in new function');
   }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="axiosFunc()">Console log</button>
</div>

CodePudding user response:

Replace your

...
.then(function (response) {
  console.log('success');
  this.testFunction();
})
...

by

...
.then(response => {
  console.log(response);
  this.testFunction();
})
...

To avoid context override.

You can also use this code:

...
.then(function (response) {
  console.log(response);
  this.testFunction();
}.bind(this))
...

Or

...
const that = this;
...
.this(function (response) {
  console.log(response);
  that.testFunction();
})
...
  •  Tags:  
  • Related