Stimulus
Docs & Examples
Source
initConfig
Defines on which selectors should stimulus apply controllers and actions dynamically once they are executed via initStimulus method.
controllers[string]
- array of controller names to apply dynamic controllers, classname and the controller need to have the same name.actions[string[]]
- array of selectors and action values to apply as dynamic actions
useStimulus
Represents the main stimulus variable on which you can register controllers.
import { useStimulus } from '../composables/stimulus.js'
useStimulus.register('x-my-component', class extends Controller {
// your code
})
initStimulus
Dynamically applies controllers and actions on selectors defined in initConfig
invoke
Registers an invoke
controller that is used to Invoke actions between controllers.
Tips
Jetbrains Plugin
Be sure to take advantage of syntax highlighting with the official Jetbrains Plugin.
Controller Communication
If you need to invoke action across controllers, you have three options
Events
Most intuitive way to communicate if the controllers have parent / children relationship.
Invoke
Handy if the controllers have no relationship. You can use our internal helper method useController
, which is an shorthand for getControllerForElementAndIdentifier
useController('x-drawer' /* controller name */, '.x-drawer' /* selector (optional) */).invoke('close', {
// event options
})
Outlets
Extending Controllers
If you need to extend a Controller, you can do so easily. Here is an example of extending Details Component.
useStimulus.register('x-details', class extends Details {
connect() {
super.connect()
this.toggleRequired(this.element.open)
}
async toggle(event) {
await super.toggle(event)
this.toggleRequired(this.element.open)
}
toggleRequired(bool) {
this.element.querySelectorAll('[data-required]').forEach((element) => {
element.required = bool
})
}
})
Do you need Stimulus?
Does your website really need Stimulus? If you are making website with minimum JavaScript, consider using native Web Components API with the Custom elements is
attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/@ungap/custom-elements/es.js"></script>
<script type="module">
customElements.define("x-header", class extends HTMLElement {
connectedCallback() {
console.log('x-header connected')
}
}, { extends: 'header' })
</script>
</head>
<body>
<header class="x-header" is="x-header">
</header>
</body>
</html>