如何不在 alpinejs 的 x-text 中出现 NAN 错误

How not to get NAN error in x-text of alpinejs

这里想获取gap属性的值,但是显示NAN错误!

    <div x-data="tamrin()">
        <h1 x-text="gap"></h1>

        <script>
            function tamrin() {
                return {
                    countTo: new Date("May 30, 2021 00:00:00").getTime(),
                    now: new Date().getTime(),
                    gap: this.countTo - this.now,
                }
            }
        </script>
    </div>

您正在返回一个对象文字,因此 this 指的是全局 window,而不是那个对象文字。

一个选项是首先创建 countTonow 变量,然后创建具有 gap 属性:

的对象

window.MyComponent = function() {
  console.log(`this === window = ${ this === window }`);
  
  const countTo = new Date('May 30, 2021 00:00:00').getTime();
  const now = new Date().getTime();

  return {
    countTo,
    now,
    gap: countTo - now,
  };
};
<div x-data="MyComponent()">
  <span x-text="gap"></span>
</div>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>

另一种选择是使用 getter and turn gap into a computed property,这样 getter 中的 this 将引用您的组件实例:

window.MyComponent = () => ({
  countTo: new Date('May 30, 2021 00:00:00').getTime(),
  now: new Date().getTime(),
  get gap() {
    console.log(`this === window = ${ this === window }`);
    
    return this.countTo - this.now;
  },
});
<div x-data="MyComponent()">
  <span x-text="gap"></span>
</div>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>

编辑:

如果要不断刷新显示值,使用第二种解决方案(getter)并更新now 属性使用setInterval:

window.MyComponent = () => ({
  countTo: new Date('May 30, 2021 00:00:00').getTime(),
  now: Date.now(),
  
  init() {
    setInterval(() => {
      requestAnimationFrame(() => {
        this.now = Date.now();
      });
    }, 200);
  },
  
  get gap() {    
    return `${ Math.round(this.countTo - this.now / 1000) } seconds left.`;
  },
});
<div x-data="MyComponent()" x-init="init">
  <span x-text="gap"></span>
</div>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>