繁体   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