<p>Web组件中的slot

slot
slot
<slot>
<p>基本用法:

<slot name="title"> <slot><script> class MyCard extends HTMLElement { constructor() { super(); const template = document.getElementById('my-card-template'); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('my-card', MyCard); </script>
<my-card> <h3 slot="title">我的卡片标题</h3> <!-- 匹配具名插槽 "title" --> <p>这是卡片的主体内容,会进入默认插槽。</p> <!-- 匹配默认插槽 --> <button slot="footer">查看更多</button> <!-- 匹配具名插槽 "footer" --> </my-card> <my-card> <!-- 只有默认内容,没有具名插槽内容 --> <p>这是另一张卡片,只有主体内容。</p> </my-card>
my-card
<h3 slot="title">
<slot name="title">
<p>
<slot>
name
my-layout
header
sidebar
main
footer
<slot name="header">
<slot name="main">
<slot>
name
<script> class ProfileCard extends HTMLElement { constructor() { super(); const template = document.getElementById('profile-card-template'); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.appendChild(template.content.cloneNode(true)); } } customElements.define('profile-card', ProfileCard); </script><slot name="avatar"> <slot>
avatar
username
description
buttons
slot
<profile-card> @@##@@ <h2 slot="username">张三</h2> <p slot="description">一位热爱前端开发的工程师,专注于Web组件和性能优化。</p> <button slot="buttons">关注</button> <button slot="buttons">私信</button> <!-- 任何没有 'slot' 属性的子元素,或者 'slot' 属性值不匹配任何具名插槽的子元素,都会被投射到默认插槽中。 --> <!-- 比如这里,如果profile-card里有默认插槽,下面这行就会被投射进去 --> <!-- <span>其他一些额外信息</span> --> </profile-card>
@@##@@
<slot name="avatar">
<button slot="buttons">
<slot name="username">匿名用户</slot> <!-- 如果没有传入 username,就显示“匿名用户” -->
::slotted()
slot
::slotted()
/* 在Shadow DOM的style标签中 */
::slotted(h2) {
color: purple; /* 样式化所有投射到插槽中的H2元素 */
border-bottom: 1px solid purple;
}
::slotted([slot="title"]) { /* 样式化所有投射到名为"title"的插槽中的元素 */
font-size: 1.5em;
}::slotted()
::slotted(div p)
click
input
host
event.target
slot
slotchange
<slot>
slotchange
assignedNodes()
assignedElements()
slot
const defaultSlot = this.shadowRoot.querySelector('slot:not([name])');
if (defaultSlot) {
const assignedNodes = defaultSlot.assignedNodes({ flatten: true }); // flatten: true 会展开嵌套的插槽内容
console.log('默认插槽内容:', assignedNodes);
}slot
slot
slot
::slotted()
slotchange

以上就是slot标签怎么用?Web组件插槽如何设置?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号