以下小计数应用程序导致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'>,如下所示:
我不知道为什么coutner
为什么被评估为undefined,尽管我使用的是箭头功能,这意味着“ this指针”的范围必须是词法的。谢谢您的建议!以下小计数应用程序导致Uncaught TypeError:在对此this.counter进行评估时,无法读取未定义的属性'counter'。
countdown
函数是一个箭头函数,这意味着其中的this
是从外部范围继承的。 setTimeout
回调也是如此。因此,这里:export default {
// ...
methods: {
countdown: () => {
setTimeout(() => {
if (--this.counter <=0){
location.href=this.$redirectURL;
} else {
this.countdown();
}
}, 1*1000);
}
},
// ...
}