ruby-on-rails 如何在rails link_to中声明刺激目标

vvppvyoh  于 2023-05-19  发布在  Ruby
关注(0)|答案(1)|浏览(131)

我正在用rails学习stimulus,并尝试在一个链接上做倒计时:
只有倒计时工作正常,我在我的控制台中得到以下错误,链接类没有更新:
1.错误:“countdown”控制器标识符缺少目标元素“countdown”:'countdown',控制器:扩展,元素:a#link.isDisabled}
1.未捕获错误:“countdown”控制器缺少目标元素“link”

我的html

<span id="countdown" data-controller="countdown" data-countdown-target="countdown"></span>
    <%= link_to 'close the windows', '#', id: 'link', class: 'isDisabled', data: { controller: 'countdown' target: 'countdown.countdown, countdown.link' } %>

我的刺激控制器

import { Controller } from "stimulus";

export default class extends Controller {
  static targets = ["countdown", "link"];

  connect() {
    this.startCountdown();
  }

  startCountdown() {
    let remainingTime = 8;
    this.updateCountdown(remainingTime);

    const countdownInterval = setInterval(() => {
      remainingTime--;
      this.updateCountdown(remainingTime);

      if (remainingTime <= 0) {
        clearInterval(countdownInterval);
        this.hideCountdown();
        this.enableLink();
      }
    }, 1000);
  }

  updateCountdown(remainingTime) {
    this.countdownTarget.innerText = remainingTime;
  }

  hideCountdown() {
    this.countdownTarget.style.display = "none";
  }

  enableLink() {
    this.linkTarget.classList.remove("isDisabled");
    this.linkTarget.classList.add("link");
  }

}
tyky79it

tyky79it1#

使用单个data-controller元素 Package 所有内容,然后为该控制器声明目标:

<span data-controller="countdown">
  <span data-countdown-target="countdown"></span>
  <%= link_to "close", "#", data: { data-countdown-target="link" } %>
</span>

如果需要,您可以在刺激控制器内引用data-controller元素本身和this.element
https://stimulus.hotwired.dev/reference/targets

相关问题