为什么这里没有定义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>发布于 2020-01-20 14:15:24
尝尝这个。
methods: {
onLogoutClick() {
let self = this
authModule.logout().then(function() {
self.$router.push("/login");
});
}发布于 2020-01-20 14:44:20
对匿名函数使用箭头函数可以解决这个问题。因为箭头函数将this绑定到词法作用域的this (在本例中是onLogoutClick的this)。
onLogoutClick() {
authModule.logout().then(() => {
this.$router.push("/login");
});
}https://stackoverflow.com/questions/59817814
复制相似问题