【问题标题】:Vue TypeError: this is undefinedVue TypeError:这是未定义的
【发布时间】:2020-05-06 03:20:59
【问题描述】:

为什么this 在这里未定义?注销时单击这是浏览器控制台中显示的错误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>

【问题讨论】:

标签: vue.js vuejs2 vue-component


【解决方案1】:

对匿名函数使用箭头函数可以解决这个问题。由于箭头函数将 this 绑定到词法范围的 this(在本例中为 onLogoutClick 的 this)。

onLogoutClick() {
    authModule.logout().then(() => {
      this.$router.push("/login");
    });
}

【讨论】:

    【解决方案2】:

    试试这个。

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

    【讨论】:

    • 通过变量显式传递它有效。但是,我正在寻找 this 成为 undeifined 的原因
    • 也许你需要将你的 onLogoutClick 函数写入方法,但我不知道为什么。
    猜你喜欢
    • 2019-12-11
    • 2021-11-04
    • 1970-01-01
    • 2020-07-13
    • 2020-11-06
    • 2021-03-26
    • 1970-01-01
    • 2020-10-08
    • 2020-01-14
    相关资源
    最近更新 更多