Reusable HTML components powered by Alpine JS reactivity 🛸
npm install alpinejs-componentReusable HTML components powered by Alpine JS reactivity 🛸
``html
defer
src="https://unpkg.com/alpinejs-component@latest/dist/component.min.js"
>
`
`shell
npm install -D alpinejs-component
yarn add -D alpinejs-component
`
`js
import Alpine from 'alpinejs'
import component from 'alpinejs-component'
Alpine.plugin(component)
Alpine.start()
`
You can render on page components by using a with an id thattemplate
matches the attribute on the component.
Here we are rendering the component HTML found in
element.
`html
x-data="{
people: [
{ name: 'John', age: '25', skills: ['JavaScript', 'CSS'] },
{ name: 'Jane', age: '30', skills: ['Laravel', 'MySQL', 'jQuery'] }
]
}"
>
$3
If you don't want on page components you can use the
url attribute which
accepts a path to the HTML component.Here we are telling Alpine JS to fetch the HTML from
/public/person.html
within the codebase.`html
x-data="{
people: [
{ name: 'John', age: '25', skills: ['JavaScript', 'CSS'] },
{ name: 'Jane', age: '30', skills: ['Laravel', 'MySQL', 'jQuery'] }
]
}"
>
url="/public/person.html"
x-data="{ item: person }"
>
Then we'd have a file
/public/person.html which could look like this.`html
`Dynamic Templates
You can pass
template or url as a dynamic value, here's an example.`html
x-data="{
components: [
{
template: '/public/person.html',
data: { name: 'John', age: '25', skills: ['JavaScript', 'CSS'] }
},
{
template: '/public/person.html',
data: { name: 'Jane', age: '30', skills: ['Laravel', 'MySQL', 'jQuery'] }
},
]
}"
>
:template="component.template"
x-data="{ item: component.data }"
> // Or
:url="component.template"
x-data="{ item: component.data }"
>
Styling Components
$3
You can use
styles attribute to specify which stylesheets to include.`html
template="person"
styles="person"
x-data="{ item: person }"
>
`You can also include multiple stylesheets by separating them with a comma.
`html
template="person"
styles="person,general"
x-data="{ item: person }"
>
`Or, if you want to include all stylesheets you can use
styles="global"$3
You can add a
Renaming Component
If you need to change the name
x-component, you can do so by setting the
global xComponent object. This is necessary because blade components start
with x-, which can cause conflicts.`js
window.xComponent = {
name: 'a-component',
}
`You will then call components like this:
`html
x-data="{
people: [
{ name: 'John', age: '25', skills: ['JavaScript', 'CSS'] },
{ name: 'Jane', age: '30', skills: ['Laravel', 'MySQL', 'jQuery'] }
]
}"
>
url="/public/person.html"
x-data="{ item: person }"
>



