Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current time and date in vue.js

I need to get current time and date in the webpage , i am having the javascript code for it . not sure how to Implement in vue.js .I am attaching the code sample here.

html and plain js code:

<html>
    <body>

        <h2>JavaScript new Date()</h2>
        <p id="timestamp"></p>

        <script>
            var today = new Date();
            var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
            var time = today.getHours() + ":" + today.getMinutes() + ":" + 
            today.getSeconds();
            var dateTime = date+' '+time;
            document.getElementById("timestamp").innerHTML = dateTime;
        </script>

    </body>
</html>

i need to implement in vue.js where should i include whether in mounted or computed or method?

like image 621
NandhaGopalElangovan Avatar asked Jul 29 '19 07:07

NandhaGopalElangovan


1 Answers

Because the time at present isn't depend on any data variable, so we can write it in methods, and call in created

Read more about computed and methods here

You can copy and run it in CodingGround

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js">
      </script>
   </head>
   <body>
      <div id = "intro" style = "text-align:center;">
         <h1>{{ timestamp }}</h1>
      </div>
      <script type = "text/javascript">
         var vue_det = new Vue({
            el: '#intro',
            data: {
               timestamp: ""
            },
            created() {
                setInterval(this.getNow, 1000);
            },
            methods: {
                getNow: function() {
                    const today = new Date();
                    const date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
                    const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                    const dateTime = date +' '+ time;
                    this.timestamp = dateTime;
                }
            }
         });
      </script>
   </body>
</html>
like image 69
vantrong291 Avatar answered Oct 24 '22 04:10

vantrong291