此示例展示了如何将 HTMX 与 Web 组件集成,从而允许它在影子 DOM 内部使用。
¥This example shows how to integrate HTMX with web components, allowing it to be used inside of shadow DOM.
默认情况下,HTMX 对你的 Web 组件一无所知,也不会看到其影子 DOM 内的任何内容。因此,你需要使用 htmx.process
手动告知 HTMX 你的组件的影子 DOM。
¥By default, HTMX doesn’t know anything about your web components, and won’t see anything inside their shadow
DOM. Because of this, you’ll need to manually tell HTMX about your component’s shadow DOM by using
htmx.process
.
customElements.define('my-component', class MyComponent extends HTMLElement {
// This method runs when your custom element is added to the page
connectedCallback() {
const root = this.attachShadow({ mode: 'closed' })
root.innerHTML = `
<button hx-get="/my-component-clicked" hx-target="next div">Click me!</button>
<div></div>
`
htmx.process(root) // Tell HTMX about this component's shadow DOM
}
})
一旦你将组件的影子 DOM 告知 HTMX,大多数事情都应该按预期工作。但是,请注意,诸如 hx-target
中的选择器将只能看到同一影子 DOM 内的元素 - 如果你需要访问 Web 组件之外的内容,则可以使用以下选项之一:
¥Once you’ve told HTMX about your component’s shadow DOM, most things should work as expected. However, note
that selectors such as in hx-target
will only see elements inside the same shadow DOM - if you need to
access things outside of your web components, you can use one of the following options:
host
:选择托管当前影子 DOM 的元素
¥host
: Selects the element hosting the current shadow DOM
global
:如果用作前缀,则从主文档而不是当前影子 DOM 中选择
¥global
: If used as a prefix, selects from the main document instead of the current shadow DOM
相同的原则通常也适用于不使用影子 DOM 的 Web 组件;虽然选择器不会像影子 DOM 那样被封装,但你仍然必须通过调用 htmx.process
将 HTMX 指向组件的内容。
¥The same principles generally apply to web components that don’t use shadow DOM as well; while selectors
won’t be encapsulated like with shadow DOM, you’ll still have to point HTMX to your component’s content by
calling htmx.process
.