Vue3 setup() 每秒更新現在時間

  
  
找了好久意外沒人寫這個
會用到reactive, ref兩種類型

輸出的結果會是:yyyy-mm-dd hh:mm:ss

以下直接上解答

<script>
import {reactive, ref} from "vue";
export default {
  name: "mainTheme",
  setup() {
    //取得時間
    let nowTime = reactive({
      data: ""
    })
    let myDate = new Date();
    function setTime(myDate) {
      const year = myDate.getFullYear();
      const month = myDate.getMonth() + 1 < 10 ? "0" + (myDate.getMonth() + 1) : (myDate.getMonth() + 1);
      const date = myDate.getDate() < 10 ? "0" + (myDate.getDate()) : myDate.getDate();
      const h = myDate.getHours();
      const m = myDate.getMinutes() < 10 ? "0" + myDate.getMinutes() : myDate.getMinutes();
      const s = myDate.getSeconds() < 10 ? "0" + myDate.getSeconds() : myDate.getSeconds();
      const time = h + ":" + m + ":" + s;
      const day = year + "-" + month + "-" + date;

      nowTime.data = day+' '+time;
    }
    function nowTimes() {
      setTime(myDate);
      setInterval(() => {
        myDate = new Date();
        setTime(myDate)
      }, 1000)
    }
    nowTimes()
    return {
      nowTime,
    }
}
}
</script>

在畫面上顯示時
輸入 {{nowTime.data}} 來顯示現在時間

  
  
  

關於站主

Shiro

因為興趣無限擴張,一直很猶豫要不要寫一個很雜的Blog,後來還是這麼做了。

聯絡:shiro050102✦gmail.com  ✦請自行更換成@

Vue