【问题标题】:querySelectorAll in a x-for loopx-for 循环中的 querySelectorAll
【发布时间】:2021-04-13 16:21:14
【问题描述】:

我试图在x-for 循环中获取所有data-xxx,但nodeList 始终为空。


<section id="content" x-data="animate()" x-init="init()">
   <h1>Title here</h1>

   <template x-for="i in items">
      <div class="box" data-class-in="fadeIn" data-class-out="fadeOut">
          <h2>Content Here</h2>
      </div>
   </template>
</section>

这是我的js代码

function animate() {
   return {
      items: 12,
      target = null,
      init: function () {
         this.target = document.querySelectorAll("[data-class-in], [data-class-out]");
         console.log(this.target);
      },
   }
}

也试过this.$el.querySelectorAll("[data-class-in], [data-class-out]")。什么都没发生

有什么帮助吗?

非常感谢

【问题讨论】:

    标签: selectors-api alpine.js


    【解决方案1】:

    您需要等待初始 x-for 渲染发生,在 Alpine 中使用 $nextTick() 完成(请参阅文档 https://github.com/alpinejs/alpine/#nexttick

    function animate() {
       return {
          items: 12,
          target = null,
          init: function () {
             // setTimeout(() => {}, 0) should also work
             this.$nextTick(() => {
               this.target = document.querySelectorAll("[data-class-in], [data-class-out]");
               console.log(this.target);
             });
          },
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2011-10-18
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多