簡體   English   中英

為什么我的 function 不能為我的時鍾加時?

[英]Why isn't my function to add time to my clock, working?

我正在學習 Vue.JS,對於我的第一個項目,我正在嘗試使用組合 API 制作數字時鍾,我遇到的問題是,function 似乎不會為我的時鍾增加時間。

這是我的代碼:

<template>
<div class="clock">
  <div class="time">
    <span>{{time}}</span>
  </div>
</div>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  name: 'App',
  setup(){
     let clock = ref(new Date())
     let time = clock.value.toLocaleTimeString('lv-LV')

    const showLocalTime = function(){
        setInterval(
          time,1000)
    };
   
    onMounted(() => {
      showLocalTime()
    })

    return{
      time
    }

  }

}
</script>

我也嘗試用onMounted替換onBeforeMount但這也沒有幫助,你能幫我理解為什么它不起作用嗎?

您需要更新時間:

 const { ref, onBeforeUnmount } = Vue const app = Vue.createApp({ setup(){ const time = ref((new Date()).toLocaleTimeString('lv-LV')) const updateCurrentTime = () => { time.value = (new Date()).toLocaleTimeString('lv-LV') } const updateTimeInterval = setInterval(updateCurrentTime, 1000) onBeforeUnmount(() => clearInterval(updateTimeInterval)) return { time } } }) app.mount('#demo')
 <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script> <div id="demo"> <div class="clock"> <div class="time"> <span>{{ time }}</span> </div> </div> </div>

clock不需要作為 ref,因為這個值在模板中沒有改變。 另一方面, time應該是一個參考,因為它每秒更新一次。

在您應該更新當前日期的時間間隔內。 為此,您需要再次調用new Date()以獲得實際日期,否則您將獲得一秒鍾前的日期並使用該舊日期更新時間。

onMounted掛鈎,因為您只更改一個變量。

您的setup()可能如下所示:

setup() {
    let now = new Date();
    const time = ref(now.toLocaleTimeString("lv-LV"));

    setInterval(() => {
      now = new Date();
      time.value = now.toLocaleTimeString("lv-LV");
    }, 1000);

    return {
      time,
    };
  },

這是一個可以的工作示例

只是讓時間參考

<template>
  <div class="clock">
    <div class="time">
      <span>{{ time }}</span>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
export default {
  setup() {
    let time = ref(new Date().toLocaleTimeString('lv-LV'))
    setInterval(() => time.value = new Date().toLocaleTimeString('lv-LV'), 1000)
    return { time }
  }
}
</script>
<template>
  <div class="clock">
    <div class="time">
      <h2>clock</h2>
      <span>{{ clock }}</span>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  name: 'App',
  setup() {
    let clock = ref()
    let time = () => {
      clock.value = new Date().toLocaleTimeString('lv-LV')
    }

    time()

    const showLocalTime = function () {
      setInterval(
          () => {
            time()
          }, 1000)
    };

    onMounted(() => {
      showLocalTime()
    })

    return {
      clock
    }

  }

}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM