我有一个web组件x-counter
,它在一个文件中。
const template = document.createElement('template');
template.innerHTML = `
<style>
button, p {
display: inline-block;
}
</style>
<button aria-label="decrement">-</button>
<p>0</p>
<button aria-label="increment">+</button>
`;
class XCounter extends HTMLElement {
set value(value) {
this._value = value;
this.valueElement.innerText = this._value;
}
get value() {
return this._value;
}
constructor() {
super();
this._value = 0;
this.root = this.attachShadow({ mode: 'open' });
this.root.appendChild(template.content.cloneNode(true));
this.valueElement = this.root.querySelector('p');
this.incrementButton = this.root.querySelectorAll('button')[1];
this.decrementButton = this.root.querySelectorAll('button')[0];
this.incrementButton
.addEventListener('click', (e) => this.value++);
this.decrementButton
.addEventListener('click', (e) => this.value--);
}
}
customElements.define('x-counter', XCounter);
这里模板被定义为使用JavaScript,并且html内容被添加为内联字符串。有没有办法将模板分离到x-counter.html
文件,css说,x-counter.css
和相应的JavaScript代码到xcounter.js
并加载它们在index.html?
我查找的每个示例都混合了Web组件。我想分离关注点,但我不知道如何使用组件。你能提供一个示例代码吗?谢谢。
在主文件中,使用<script>
加载Javascript文件x-counter.js
。
在Javascript文件中,使用fetch()
加载HTML代码x-counter.html
。
在HTML文件中,使用<link rel="stylesheet">
加载CSS文件x-counter.css
。
CSS文件:x-counter.css
button, p {
display: inline-block;
color: dodgerblue;
}
HTML文件:x-counter.html
<link rel="stylesheet" href="x-counter.css">
<button aria-label="decrement">-</button>
<p>0</p>
<button aria-label="increment">+</button>
Javascript文件:x-counter.js
fetch( "x-counter.html" )
.then( stream => stream.text() )
.then( text => define( text ) )
function define( html )
{
class XCounter extends HTMLElement {
set value(value) {
this._value = value;
this.valueElement.innerText = this._value;
}
get value() {
return this._value;
}
constructor() {
super();
this._value = 0;
var shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = html;
this.valueElement = shadow.querySelector('p');
var incrementButton = shadow.querySelectorAll('button')[1];
var decrementButton = shadow.querySelectorAll('button')[0];
incrementButton.onclick = () => this.value++;
decrementButton.onclick = () => this.value--;
}
customElements.define('x-counter', XCounter);
}
主要档案:index.html
<html>
<head>
<script src="x-counter.js"></script>
<body>
<x-counter></x-counter>