Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue: timer value doesn't update when using setInterval

I have the following code for updating the number of seconds elapsed and displaying it:

<template>
 
 <div>
   {{timerValue}}
   
 </div>
 
  </template>

<script>
 export default {
  name: "App",
  components: {
     
  },

  data() {
    return {
      timerValue: ""
    }
  },

  created()  {
     let seconds = 0;
      this.timerValue = seconds;
      setInterval(function()  {
           seconds++;
      })
  }
};
</script>

However the page always displays

0

What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

https://codesandbox.io/s/still-cache-1mdgr6?file=/src/App.vue

>Solution :

Maybe like following snippet:

const app = Vue.createApp({
  data() {
    return {
      timerValue: ""
    }
  },
  created()  {
      setInterval(() => {
           this.timerValue++;
      }, 1000)
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div>
    {{timerValue}}
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading