如何在 alpine.js 应用程序中制作具有时间间隔的计时器

问题描述 投票:0回答:1
alpine.js
1个回答
13
投票

以下方法可行吗?

您可能想要对 Alpine.js 执行的是更新一个

time
变量(使用 setInterval),然后您可以使用
this.time
和相关 Moment.js 表达式读取格式化时间。

<div>
    <div x-data="appFooterComponent()" x-init="init()">
        <div>
            ...
            <span style="background-color: yellow" x-text="getTime()"></span>
        </div>
    </div>
</div>

<script>
    function appFooterComponent() {
        return {
            time: new Date(),
            init() {
              setInterval(() => {
                this.time = new Date();
              }, 1000);
            },
            getTime() {
                return moment(this.time).format('DD MMMM, YYYY HH:mm:ss')
            },
        }
    } 

</script>
© www.soinside.com 2019 - 2024. All rights reserved.