hdk
hdk

Reputation: 900

Vue TypeError: this is undefined

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>

Upvotes: 1

Views: 2966

Answers (2)

hdk
hdk

Reputation: 900

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");
    });
}

Upvotes: 0

&#214;mer Doğan
&#214;mer Doğan

Reputation: 691

try this.

     methods: {
       onLogoutClick() {
        let self = this
        authModule.logout().then(function() {
          self.$router.push("/login");
        });
      }

Upvotes: 1

Related Questions