我有一个父组件,其中我使用 ref 调用函数 startTimer() ,并且我想直接在子组件中停止此计时器,但这不起作用。我在某处读到 setInterval 中的箭头函数可能会出现问题,但这对我来说没有什么区别,所以我继续使用箭头函数。
父组件
<template>
<child-component ref="child" />
<button @click="startTimer">Start Timer</button>
</template>
<script>
export default {
components: {
ChildComponent
},
methods: {
startTimer() {
this.$refs.child.startTimerInChild()
}
}
}
</script>
子组件
<template>
<button @click="stopTimer">Stop Timer</button>
</template>
<script>
export default {
methods: {
startTimerInChild() {
this.timer = setInterval(() => {
doSomethingEveryTwoSeconds();
}, 2000);
},
stopTimer() {
clearInterval(this.timer)
}
},
data() {
return {
timer: null
}
}
}
</script>
(我在这个项目中仍然使用Vue2,不知道这是否重要)
我发现的唯一类似问题是这个,但我找不到适合我的场景的解决方案: setInterval on child component method called with refs to child at parent component
最佳答案
我认为在父组件中管理状态是一个很好的做法。因此,我认为您需要将间隔和存储它的变量移动到父组件,并在处理方法 stopTimer
时使用 $emit('stop')
(或其他)并使用 @stop="stopTimer"
在父级中捕获它(或再次使用 smth else)并使用 clearInterval(this.timer)
将其停止在那里然后是父级中的状态。
关于vuejs2 - 如果 setInterval 是通过 vue2 中父组件的 ref 调用的,如何清除Interval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75732746/