
本文旨在解决在 Rails 应用中使用 Stimulus.js 时,如何正确地在 link_to 辅助方法中声明和使用 target。我们将通过一个倒计时的例子,讲解如何将 link_to 元素与 Stimulus controller 关联,并解决常见的 "Missing target element" 错误。本文将提供清晰的代码示例和详细的解释,帮助你更好地理解和应用 Stimulus.js。
在使用 Stimulus.js 构建交互式 Rails 应用时,正确地声明和使用 target 至关重要。Target 允许 controller 直接与 HTML 元素交互,从而实现动态更新和行为控制。本文将通过一个倒计时的例子,详细介绍如何在 Rails 的 link_to 辅助方法中正确声明和使用 target,避免常见的错误。
在提供的示例中,开发者尝试在 link_to 元素上实现一个倒计时功能,但遇到了 "Missing target element" 错误。主要问题在于 target 的声明方式和 controller 的作用域。
解决此问题的关键是将所有相关的 HTML 元素包裹在一个具有 data-controller 属性的父元素中,然后在这个父元素上声明所有 target。
HTML 结构:
<span data-controller="countdown">
<span data-countdown-target="countdown"></span>
<%= link_to "close", "#", data: { countdown_target: "link" } %>
</span>解释:
Stimulus Controller 代码:
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");
}
}解释:
通过将相关的 HTML 元素包裹在一个 data-controller 属性的父元素中,并在父元素上声明所有 target,可以有效地解决 "Missing target element" 错误,并实现 Stimulus.js controller 与 Rails link_to 元素的无缝集成。 理解 Stimulus 的作用域和 target 的声明方式是构建健壮的交互式 Rails 应用的关键。
以上就是在 Rails link_to 中正确声明 Stimulus Target的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号