Getting current time and date in vue.js

前端 未结 1 466
北海茫月
北海茫月 2021-02-09 01:49

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.

h

相关标签:
1条回答
  • 2021-02-09 02:31

    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>
    
    0 讨论(0)
提交回复
热议问题