2

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

MrBrighter
  • 21
  • 3

1 Answers1

2

I think it is good practise to manage state in the parent component. So I think you need to move your interval and the variable you store it in up to the parent component, and on handling the method stopTimer use $emit('stop') (or smth else) and catch it in the parent using @stop="stopTimer" (or smth else again) and stop it there using clearInterval(this.timer) which is then state in the parent.

Lars Vonk
  • 623
  • 5
  • 13