假设我有一个对话框组件,例如
class ModalDialog extends HTMLElement {
constructor(){
super()
this._shadow = this.attachShadow({mode: 'closed'})
}
connectedCallback(){
const template = `
<style>
... lots of style that doesn't matter to this question ...
</style>
<div class="dialog">
<div class="dialog-content">
<div class="dialog-header">
<slot name="header"></slot>
<span class="close">×</span>
</div>
<div class="dialog-body"><slot name="body"></slot></div>
<div class="dialog-footer"><slot name="footer"></slot></div>
</div>
</div>
`
this._shadow.innerHTML = template
this._shadow.querySelector('.close').onclick = () => this.hide()
const dialog = this._shadow.querySelector('.dialog')
dialog.onclick = evt => {
if(evt.target == dialog){ //only if clicking on the overlay
this.hide()
}
}
this.hide()
}
show() {
this.style.display = 'block'
}
hide(){
this.style.display = 'none'
}
}
window.customElements.define('modal-dialog', ModalDialog)
现在假设我想创建专用对话框……例如,允许用户选择图像的对话框。
我可以这样做
import {} from './modal-dialog.js'
class ImageSelector extends HTMLElement {
constructor(){
super()
this._shadow = this.attachShadow({mode: 'closed'})
}
connectedCallback(){
const template = `
<style>
... more style that doesn't matter ...
</style>
<modal-dialog>
<div slot="header"><h3>Select Image</h3></div>
<div slot="body">
... pretend there's some fancy image selection stuff here ...
</div>
</modal-dialog>
`
this._shadow.innerHTML = template
}
show(){
this._shadow.querySelector('modal-dialog').show()
}
hide(){
this._shadow.querySelector('modal-dialog').hide()
}
}
window.customElements.define('image-selector', ImageSelector)
但我不喜欢show
andhide
方法,那里。
另一种选择是从对话框继承而不是从HTMLElement
...
import {} from './modal-dialog.js'
class ImageSelector extends customElements.get('modal-dialog'){
constructor(){
super()
}
connectedCallback(){
... now what? ...
}
}
window.customElements.define('image-selector', ImageSelector)
但如果我这样做,我该如何填补空缺?
天真的方法当然是使用_shadow
并将其放入插槽的内部 html 中,但我有一种感觉,这不是要走的路。