0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[自分用メモ]stimulusと普通のjsの違い

0
Last updated at Posted at 2026-02-10

普通のJSの場合と、Stimulusの場合でコードを比較してみましょう。
今回は、簡単なカウンター処理で比較してみます。

普通のJSの場合

<div>
  <button id="increment-button">増やす</button>
  <p>現在のカウント: <span id="count-display">0</span></p>
</div>
const button = document.querySelector('#increment-button');
const display = document.querySelector('#count-display');
let count = 0;

button.addEventListener('click', () => {
  count++;
  display.textContent = count;
});
  • HTML: 「ここでこういうことをするとこうなるんだな」というのが分かりづらいです。
  • JS: document.querySelector のようなDOM探索の記述を書かないといけません。

Stimulusの場合

<div data-controller="counter">
  <button data-action="click->counter#increment">増やす</button>
  <span data-counter-target="display">0</span>
</div>
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["display"]

  count = 0

  increment() {
    this.count++
    this.displayTarget.textContent = this.count
  }
}
  • HTML: 「ここをクリックすると、counterコントローラのincrementアクションが実行されるんだな」と分かりやすいです。また、targetを指定する書き方なので、どこが操作対象なのかが分かりやすいです。
  • JS: static targets = ["display"] と定義するだけで、Stimulusが this.displayTarget といったプロパティを自動で追加してくれるので、document.querySelector を書く必要がありません(参考:https://stimulus.hotwired.dev/reference/targets )。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?