[Vuejs]-Laravel/Vue.js โ€“ Timer

0๐Ÿ‘

โœ…

I could provide you a solution which simulates your use case, by defining a method to fetch data from database (in my case an online API which provide the current date and time) and call that method in created hook, and by taking advantage of setInterval function we could get data every second.

Run this code snippet that i hope it could help you :

new Vue({
  el: '#app',
  data() {
    return {
      now: 0
    };
  },
  created: function() {

    this.fetchTemp('https://script.googleusercontent.com/a/macros/esi.dz/echo?user_content_key=ypoXRw1nVHj-h1VRDmh6TXSI1VpIPWW7Qo2n9El6RqoxAJ3v28nBI9bDY_4UAE0TQJ3pSozxpbTiRvFpmD8pvcTkGSnPAtgRm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_nRPgeZU6HP_B2BW4qWwVPUuHIcJ3mEdrfLIfNZsYUQi0c--vxV_3BX606CngcowlqSfFH8SSiqMPrUuXDMsd72r-P39_jlVDMh0BMLnMwXU02UuEHWiuob4ULL2SJgrtyBAf43AAwP8&lib=MwxUjRcLr2qLlnVOLh12wSNkqcO1Ikdrk');

    setInterval(() => {
      this.fetchTemp('https://script.googleusercontent.com/a/macros/esi.dz/echo?user_content_key=ypoXRw1nVHj-h1VRDmh6TXSI1VpIPWW7Qo2n9El6RqoxAJ3v28nBI9bDY_4UAE0TQJ3pSozxpbTiRvFpmD8pvcTkGSnPAtgRm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_nRPgeZU6HP_B2BW4qWwVPUuHIcJ3mEdrfLIfNZsYUQi0c--vxV_3BX606CngcowlqSfFH8SSiqMPrUuXDMsd72r-P39_jlVDMh0BMLnMwXU02UuEHWiuob4ULL2SJgrtyBAf43AAwP8&lib=MwxUjRcLr2qLlnVOLh12wSNkqcO1Ikdrk');

    }, 1000);
  },

  methods: {

    fetchTemp(uri) {

      axios.get(uri).then((res) => {
        this.now = new Date(res.data.fulldate).toLocaleString();


      }).catch(err => {});
    }
  }
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script>
</head>

<body>
  <div id="app">
    <h1> Now : {{now}} </h1>
  </div>
</body>

</html>

Leave a comment