rails webpacker:install:stimulus
yarn install
bin/webpack-dev-serverCopy
"stimulus" : "^2.0.0" ,Copy
<div data-controller="hello" data-hello-number-value=4>
<%# <h1 data-target="hello.output" ></h1> %>
<h1 data-hello-target='output' ></h1>
<button data-action='hello#clicked' >CLICK ME</button>
</div>
<div data-controller="text-input" >
<input type ="text" data-action="text-input#changed" data-text-input-target="input" >
<h1 data-text-input-target='output' ></h1>
</div>
<div data-controller="styling"
data-styling-primary-class="btn-primary" >
<button class='btn' data-styling-target='button' data-action='styling#clicked' >
CLICK ME
</button>
</div>
<div data-controller="styling"
data-styling-primary-class="btn-primary" >
<button class='btn' data-styling-target='button' data-action='styling#clicked' >
CLICK ME
</button>
<button data-action="styling#clicked:once" >CLICK ONCE</button>
</div>Copy
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "output" ]
static values = { number: Number }
connect() {
this.numberValueChanged()
}
clicked() {
this.numberValue++
}
numberValueChanged() {
this.outputTarget.textContent = this.numberValue
}
}Copy
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["button" ]
static classes = ["primary" ]
connect() {
this.buttonTarget.classList.add(this.primaryClass)
}
clicked() {
this.buttonTarget.classList.toggle(this.primaryClass)
}
}Copy
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["input" , "output" ]
connect() {}
changed() {
this.outputTarget.textContent = this.inputTarget.value
}
}Copy