【问题标题】:How can I get the value of a data-attribute in an Alpine.js component?如何获取 Alpine.js 组件中数据属性的值?
【发布时间】:2021-07-08 23:25:00
【问题描述】:

我正在尝试将我的组件中的data-countdown 值(日期和时间)导入x-data,以便我可以从中创建一个倒数计时器。

我浏览了文档,但找不到任何可以帮助我获得价值的东西。我将x-model 用于输入的值,但由于这不会改变,我只需要访问该值。

我用x-bind 尝试过,但没有成功。

这是一个刀片文件。我在roots-sage中使用它。

<div class='countdown' x-bind:data-countdown="{ 'time': {{ $class[time][day] }} {{ $class[time][time] }} }">
</div>

这是我的 JavaScript 代码。

window.singleGroupClass = function () {
  return {
    data: 'hey',
    time: console.log(this.el),
    countdown() {
      console.log(this);
    },
  }
}

【问题讨论】:

    标签: javascript alpine.js


    【解决方案1】:

    使用 Alpine.js 实现整个事情的方式可能类似于以下内容。

    请注意,您需要在 {{ $class[time][day] }} {{ $class[time][time] }} 周围加上引号。

    <div class='countdown' x-data="singleGroupClass({ 'time': '{{ $class[time][day] }} {{ $class[time][time] }}' })">
    </div>
    <script>
      window.singleGroupClass = function (seedData) {
        return {
          time: seedData.time,
          countdown() {
            console.log(this);
          },
        }
      }
    </script>
    

    或者,如果您绝对需要使用data-countdown 属性中的值:

    <div class='countdown' x-data="{ time : $el.dataset.countdown }" data-countdown="{{ $class[time][day] }} {{ $class[time][time] }}">
      <div x-text="time"></div>
    </div>
    

    请注意,data-countdown="{ 'time': '{{ $class[time][day] }} {{ $class[time][time] }}' }" 会很困难,因为您需要将其解析为 JSON(可能)。

    【讨论】:

    • 这正是我想要的。我只需要访问该值。我可以删除 data-countdown 属性。非常感谢!
    • 嘿@Hugo,虽然这可行,但它也会引发错误:Uncaught (in promise) SyntaxError: Invalid or unexpected token at new Function (&lt;anonymous&gt;)
    • 嘿,我解决了。是同一组件中的其他代码引发了错误。
    【解决方案2】:

    尝试,在 Html 中

    <div x-data="alpineComponent()" id="reviews" data-reviews='<?= $dataObj ?>'></div>
    

    在 Js 中

    {
      return {
        reviews: JSON.parse(document.getElementById('reviews').dataset.reviews)
      }
    }
    

    【讨论】:

    • 虽然此代码可以回答问题,但提供有关 如何 和/或 为什么 解决问题的附加上下文将改善答案的长期价值。
    猜你喜欢
    • 2021-08-14
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多