問題一覧に戻る
中級ビューとアセット
問題49: Stimulus - JavaScriptフレームワーク基礎

Rails用の控えめなJavaScriptフレームワーク、Stimulusの基礎を学習します。Stimulusはシンプルな規約を使ってJavaScriptオブジェクトをHTML要素に接続します。HTMLにちょうど良い量の振る舞いを追加して動的にし、コードを整理された保守しやすい状態に保つよう設計されています。

<!-- HTML -->
<!-- rails.problems.49.comments.dataController -->
<div data-="hello">
<!-- rails.problems.49.comments.dataTarget -->
<input type="text" data-hello-="name">

<!-- rails.problems.49.comments.dataAction -->
<button data-="click->hello#greet">
Greet
</button>

<span data-hello-target="output"></span>
</div>

// JavaScript
// rails.problems.49.comments.controllerClass
import { Controller } from "@hotwired/stimulus"

export default class extends {
static targets = ["name", "output"]

greet() {
this.outputTarget.textContent =
`Hello, ${this.nameTarget.value}!`
}
}