gpt4 book ai didi

javascript - 如何将 Web 组件分离到单个文件并加载它们?

转载 作者:行者123 更新时间:2023-11-30 06:10:39 24 4
gpt4 key购买 nike

我有一个网络组件 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>
</head>
<body>
<x-counter></x-counter>
</body>
</html>

关于javascript - 如何将 Web 组件分离到单个文件并加载它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59051509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com