Search code examples
javascriptvue.jssetintervalvue-reactivity

Vue data updates in method with setInterval() but the dom/view doesn't update


In my methods I have a function which is triggered using a @click in the view. This functions starts a timer, the timer works as I can see in the DevTools but it only updates in the DevTools when I hit refresh.

Also in the view the timer isn't shown at all as it is only rendered in once and it's not looking for updates.

UPDATED: Full code on request

<template>
<div class="container-fluid">
    <div class="card mt-2 p-3 w-75 mx-auto">
        <h2>League Summoners Timers</h2>
        <hr>
        <div>
            <h5>Enemy team</h5>
            <div class="row">
                <div class="col-md-12 col-lg-2" v-for="index in lanes" :key="index">
                    <div class="card">
                        <div class="card-header">
                            <p class="m-0">{{ index }}</p>
                        </div>
                        <div class="card-body">
                            <div v-show="!gameStarted">
                                <div v-show="selected[index.toLowerCase()].length < 2" class="spell-image-row" v-for="spell in spells" :key="spell.name" @click="onClickSelection(spell, index)">
                                    <img class="spell-image m-1" :alt="spell.name" :src="spell.image">
                                </div>
                                <div v-show="selected[index.toLowerCase()].length >= 2">
                                    <span class="alert alert-primary">Spells selected</span>
                                    <ul class="mt-3">
                                        <li v-for="selectedSpell in selected[index.toLowerCase()]" :key="selectedSpell">
                                            {{ selectedSpell }}
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div v-show="gameStarted">
                                <div v-for="spell in selected[index.toLowerCase()]" :key="index+spell">
                                    <div class="row">
                                        <img style="float: left" class="my-1" :src="spells[spell.toLowerCase()].image" :alt="spell.name" @click="onClickStartTimer(spell, index)">
                                        <p>{{ timers[index.toLowerCase()][spell.toLowerCase()] }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="mt-3">
            <button class="btn btn-primary mr-3" @click="gameStarted = true" v-show="checkSelected() && !gameStarted">Start game</button>
            <button class="btn btn-danger" onClick="window.location.reload();">Reset</button>
        </div>
    </div>
</div>

<script>
    export default {
        name: "LeagueTimers",
        data() {
            return {
                gameStarted: false,
                lanes: ['Top', 'Jungle', 'Mid', 'ADC', 'Support'],
                spells: {
                    teleport: {
                        name: 'Teleport',
                        image: require('../assets/images/Teleport.png'),
                        cooldown: 420,
                    },
                    ignite: {
                        name: 'Ignite',
                        image: require('../assets/images/Ignite.png'),
                        cooldown: 180,
                    },
                    heal: {
                        name: 'Heal',
                        image: require('../assets/images/Heal.png'),
                        cooldown: 240,
                    },
                    ghost: {
                        name: 'Ghost',
                        image: require('../assets/images/Ghost.png'),
                        cooldown: 300,
                    },
                    flash: {
                        name: 'Flash',
                        image: require('../assets/images/Flash.png'),
                        cooldown: 300,
                    },
                    exhaust: {
                        name: 'Exhaust',
                        image: require('../assets/images/Exhaust.png'),
                        cooldown: 210,
                    },
                    cleanse: {
                        name: 'Cleanse',
                        image: require('../assets/images/Cleanse.png'),
                        cooldown: 210,
                    },
                    barrier: {
                        name: 'Barrier',
                        image: require('../assets/images/Barrier.png'),
                        cooldown: 180,
                    },
                    smite: {
                        name: 'Smite',
                        image: require('../assets/images/Smite.png'),
                        cooldown: 15,
                    },
                },
                selected: {
                    top: [],
                    jungle: [],
                    mid: [],
                    adc: [],
                    support: [],
                },
                timers: {
                    top: {},
                    jungle: {},
                    mid: {},
                    adc: {},
                    support: {},
                },
            }
        },
        methods: {
            onClickSelection(spell, lane) {
                this.selected[lane.toLowerCase()].push(spell.name);

            },
            onClickStartTimer(spell, lane) {
                if (!this.timers[lane.toLowerCase()][spell.toLowerCase()]) {
                    this.startTimer(spell.toLowerCase(), lane.toLowerCase(), this.spells[spell.toLowerCase()].cooldown);
                } else {
                    console.log('runt al');
                }
            },
            checkSelected() {
                for (let [key] of Object.entries(this.selected)) {
                    if (this.selected[key].length !== 2) {
                        return false;
                    }
                }
                return true;
            },
            startTimer(spell, lane, cooldown) {
                this.timers[lane][spell] = cooldown;
                let timers = this.timers;
                setInterval(function (){
                    timers[lane][spell]--;
                    // console.log(lane+spell + " - " + timers[lane][spell]);
                    // console.log(typeof timers[lane][spell])
                    this.$forceUpdate();
                }, 1000);
            },
        },
    }
</script>

What I've tried to far is using watch: {} and computed: {} but nothing has worked so far. I have to add that I'm pretty new to Vue.


Solution

  • try to declare your setInterval function this way

     setInterval(() => {
        this.timers[lane][spell]--;
        console.log(lane+spell + " - " + timers[lane][spell]);
        console.log(typeof timers[lane][spell])
        // this.$forceUpdate();
      }, 1000);
    

    Using an arrow function, you have access to the properties data using this.timers. Using Function syntax will create a new scope, and this.timers is not available

    If you want to use the function syntax, you can bind the this object by this way

      setInterval(function () {
        this.timers[lane][spell]--;
        console.log(lane+spell + " - " + timers[lane][spell]);
        console.log(typeof timers[lane][spell])
      }.bind(this), 1000)
    

    Also, to add reactivity to the objects inside the data property timers, you must declare them initially:

    timers:
      { top:
        { teleport: 0,
          smite: 0, 
          ... },
        ...
       }
    

    If you want to add dynamically these properties, the vue set property is the way to do it, you can read more about it here https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats