javascript 在 vue.js 中获取当前时间和日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/57249466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:39:22  来源:igfitidea点击:

Getting current time and date in vue.js

javascriptvue.js

提问by saran

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.

我需要在网页中获取当前时间和日期,我有它的 javascript 代码。不知道如何在 vue.js 中实现。我在这里附上代码示例。

html and plain js code:

html 和纯 js 代码:

<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?

我需要在 vue.js 中实现,我应该在安装、计算还是方法中包含?

回答by vantrong291

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

因为目前的时间不依赖于任何数据变量,所以我们可以把它写在methods中,在created中调用

Read more about computedand methodshere

在此处阅读有关计算方法的更多信息

You can copy and run it in CodingGround

您可以在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>