我正在用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");
}
}
1条答案
按热度按时间tyky79it1#
使用单个
data-controller
元素 Package 所有内容,然后为该控制器声明目标:如果需要,您可以在刺激控制器内引用
data-controller
元素本身和this.element
。https://stimulus.hotwired.dev/reference/targets