I have a parent in which I call a function startTimer() with a ref and I want to stop this Timer directly within the child component but that doesn't work. I read somewhere that arrow functions in the setInterval can make problems but it did not make a difference for me so i stayed with the arrow functions.
Parent Component
<template>
<child-component ref="child" />
<button @click="startTimer">Start Timer</button>
</template>
<script>
export default {
components: {
ChildComponent
},
methods: {
startTimer() {
this.$refs.child.startTimerInChild()
}
}
}
</script>
Child Component
<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>
(I still use Vue2 in this project, don't know if that matters)
Only similar problem I found was this but I couldn't find a solutions that works for my scenario: setInterval on child component method called with refs to child at parent component