为什么我在SetTimeout中使用箭头功能,但仍然收到“ Uncaught TypeError:无法读取未定义的属性'counter'”]]

问题描述 投票:2回答:1

以下小计数应用程序导致Uncaught TypeError:无法读取未定义的属性'counter'

在对此this.counter进行评估时。
<template>
  <v-app>
    <v-content>
      Redirect after {{counter}} sec.
    </v-content>
  </v-app>
</template>

<script>
/* eslint-disable no-console */
export default {
  name: 'App',

  components: {
  },
  mounted() {
    this.countdown();
  },
  created() {
  },
  methods: {
    countdown: () => {
      setTimeout(() => {
        if (--this.counter <=0){
          location.href=this.$redirectURL;
        } else {
          this.countdown();
        }
      }, 1*1000);
    }
  },

  data: () => ({
    counter: 5,
  }),
};
</script>

Uncaught TypeError:无法读取未定义的属性'counter'>,如下所示:

enter image description here

我不知道为什么coutner

为什么被评估为undefined,尽管我使用的是箭头功能,这意味着“ this指针”的范围必须是词法的。谢谢您的建议!

以下小计数应用程序导致Uncaught TypeError:在对此this.counter进行评估时,无法读取未定义的属性'counter'。

javascript vue.js settimeout arrow-functions
1个回答
4
投票
countdown函数是一个箭头函数,这意味着其中的this是从外部范围继承的。 setTimeout回调也是如此。因此,这里:

export default { // ... methods: { countdown: () => { setTimeout(() => { if (--this.counter <=0){ location.href=this.$redirectURL; } else { this.countdown(); } }, 1*1000); } }, // ... }

© www.soinside.com 2019 - 2024. All rights reserved.