1

I' having issue with the code given,

submit () {
    fetch(this.url + "/auth/login",{
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        mobilenumber: this.form.mobilenumber,
        password: this.form.password})
    }).then(function (response) {
      console.log("Response = " + response.status);
      if (response.status == 200) {
          this.$router.push({
             name: "Users",
          })
      } else {
          alert("Not logged in");
      }
      return response.json();
    }).then(function (data) {
      
    }).catch(function (error) {
      console.log("-------- error ------- " + error);  
    });
}

When the submit function is called I want to navigate to Users page. I have written this.$router.push({ name: "Users" }) for that. But I am getting error in the console:

Cannot read property '$router' of undefined.

I tried self.$router.push({ name: "Users" }). Still I am getting the same error in console. Pls help.

Helen
  • 58,317
  • 8
  • 161
  • 218
  • Does this answer your question? [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Aluan Haddad Sep 17 '20 at 17:18

1 Answers1

1

You need the reference to the outer scope because in the fetch callback this is undefined. To resolve this, you can create a reference of the outer scope by creating a reference as,

submit () {
    let self = this;
    ...

Then, You can use the reference as,

self.$router.push({
    name: "Users",
})
Kiran Maniya
  • 5,637
  • 4
  • 34
  • 53