- Web Component中使用slot的使用方式与vue中slot很像,或许后者借用了前者的思想。
-
Web Component支持具名slot和默认slot,见下例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>shadowDom 示例</title>
<script>
const template = document.createElement('template');
template.innerHTML = `
<style>
.container {
padding: 8px;
}
button {
display: block;
overflow: hidden;
position: relative;
padding: 0 16px;
font-size: 16px;
font-weight: bold;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
outline: none;
width: 100%;
height: 40px;
box-sizing: border-box;
border: 1px solid #a1a1a1;
background: #ffffff;
box-shadow: 0 2px 4px 0 rgba(0,0,0, 0.05), 0 2px 8px 0 rgba(161,161,161, 0.4);
color: #363636;
cursor: pointer;
}
</style>
<div class="container">
<slot>slot default</slot>
<hr>
<slot name="slot1">slot1</slot>
<button>Label</button>
<slot name="slot2">slot2</slot>
</div>
`;
var modeStatus = 'open'
class Button extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({ mode: modeStatus });
this._shadowRoot.appendChild(template.content.cloneNode(true));
}
}
window.customElements.define('my-button', Button);
</script>
</head>
<body>
<my-button>
<div slot="slot1">我是slot1</div>
<div slot="slot2">我是slot2</div>
<div>我是默认slot</div>
</my-button>
</body>
</html>