1

Why this is undefined here? On logout click this is the error shown in the browser console TypeError: this is undefined

<script lang="ts">
import Vue from "vue";
import { getModule } from "vuex-module-decorators";
import Component from "vue-class-component";
import AuthModule from "@/store/auth";
import Store from "@/store";

const authModule = getModule(AuthModule, Store);

@Component({})
export default class App extends Vue {
  mounted() {
    console.log("App mounted");
  }
  onLogoutClick() {
    authModule.logout().then(function() {
      this.$router.push("/login");
    });
  }
 }
</script>
hdk
  • 720
  • 2
  • 9
  • 19
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – AT82 Jan 20 '20 at 12:43

2 Answers2

1

try this.

     methods: {
       onLogoutClick() {
        let self = this
        authModule.logout().then(function() {
          self.$router.push("/login");
        });
      }
Seb
  • 363
  • 1
  • 18
Ömer Doğan
  • 501
  • 1
  • 6
  • 21
  • Passing this explicitly via a variable works. But, I was looking for the reason for `this` to be `undeifined` – hdk Jan 20 '20 at 06:17
  • maybe you need to write into methods your onLogoutClick function, but i dont know why. – Ömer Doğan Jan 20 '20 at 06:24
0

Using an arrow function to the anonymous function solves this. As arrow functions bind this to the lexical scope's this (in this case onLogoutClick's this).

onLogoutClick() {
    authModule.logout().then(() => {
      this.$router.push("/login");
    });
}
blackgreen
  • 34,072
  • 23
  • 111
  • 129
hdk
  • 720
  • 2
  • 9
  • 19