【发布时间】:2021-01-07 15:22:21
【问题描述】:
我在我的 vue 应用程序中使用 vue-router。在我的一个组件中,我在 requestAnimationFrame 中有一个简单的计数器。但是每次我从 Page2 (计数器所在的位置)更改为 Page1 并返回到 Page2 时,我似乎都得到了我的计数器的一个新实例。我该如何解决,以便在交换页面时完全删除我的最后一个计数器?用下图说明问题:
两次进入第2页后
如你所见,两个数列向上计数
我也尝试删除 debugInc 的实例,但得到:
this.debugInc.destroy is not a function
我的代码在下面和这里的 repo 中: https://github.com/reppoper/forumpost
App.vue
<template>
<div id="app">
<router-link to="/">Page1</router-link> |
<router-link to="/page2">Page2</router-link>
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
components: {
}
}
</script>
Helloworld.vue
<template>
<div class="hello">
<h1>HELLO</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
}
</script>
Goodbyeworld.vue(计数器在哪里)
<template>
<div class="hello">
<h1>GOODBYE</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data: function () {
return {
debugInc: 0,
};
},
created() {
this.loop();
},
methods: {
loop() {
requestAnimationFrame(this.loop);
console.log(this.debugInc);
this.debugInc = this.debugInc + 1;
if (this.debugInc > 59) {
this.debugInc = 0;
}
},
},
beforeDestroy() {
console.log("DESTROY");
this.debugInc.destroy();
},
};
</script>
我的看法:
Page1.vue
<template>
<div>
<HelloWorld/>
</div>
</template>
<script>
import HelloWorld from "../components/HelloWorld.vue";
export default {
components: {
HelloWorld
}
}
</script>
Page2.vue
<template>
<div>
<GoodbyeWorld />
</div>
</template>
<script>
import GoodbyeWorld from "../components/GoodbyeWorld.vue";
export default {
components: {
GoodbyeWorld,
},
};
</script>
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component vue-router