Mozilla表示Web components由三个主要技术组成:
在ECMAscript的模板文字的背景下,编号3“HTML模板”是否必要?
看看我从James Milner那里得到的这个例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web Component</title>
<script type="text/javascript">
// We define an ES6 class that extends HTMLElement
class CounterElement extends HTMLElement{
constructor() {
super();
// Initialise the counter value
this.counter = 0;
// We attach an open shadow root to the custom element
const shadowRoot= this.attachShadow({mode: 'open'});
// We define some inline styles using a template string
const styles=`
:host {
position: relative;
font-family: sans-serif;
}
#counter-increment, #counter-decrement {
width: 60px;
height: 30px;
margin: 20px;
background: none;
border: 1px solid black;
}
#counter-value {
font-weight: bold;
}
`;
// We provide the shadow root with some HTML
shadowRoot.innerHTML = `
<style>${styles}</style>
<h3>Counter</h3>
<slot name='counter-content'>Button</slot>
<button id='counter-increment'> - </button>
<span id='counter-value'> 0 </span>
<button id='counter-decrement'> + </button>
`;
// We can query the shadow root for internal elements
// in this case the button
this.incrementButton = this.shadowRoot.querySelector('#counter-increment');
this.decrementButton = this.shadowRoot.querySelector('#counter-decrement');
this.counterValue = this.shadowRoot.querySelector('#counter-value');
// We can bind an event which references one of the class methods
this.incrementButton.addEventListener("click", this.decrement.bind(this));
this.decrementButton.addEventListener("click", this.increment.bind(this));
}
increment() {
this.counter++
this.invalidate();
}
decrement() {
this.counter--
this.invalidate();
}
// Call when the counter changes value
invalidate() {
this.counterValue.innerHTML = this.counter;
}
}
// This is where the actual element is defined for use in the DOM
customElements.define('counter-element', CounterElement);
</script>
</head>
<body>
<counter-element></counter-element>
</body>
</html>
注意他没有使用HTML模板,而是使用ecmascript模板字面量来设置shadowRoot的innerHTML。
此后,他使用querySelector获取shadowRoot的内部元素,并最终为增量和减量按钮添加事件侦听器。
如果您使用HTML模板而不是ecmascript模板字面量,这会给您带来什么好处?
从概念上讲,我很难找到一个情况,我更喜欢使用HTML模板元素而不是Ecmascript模板字面量。
请给予建议。
<template>
元素似乎不受IE支持。 - CertainPerformance<script type="text/template" id="postTemplate">
代替<template>
。有关jquery的示例,请参见:https://stackoverflow.com/questions/52376527/populate-grid-div-p-with-json-data-file/52376863#52376863。实际上并不需要jQuery,这只是我找到的第一个例子。 - Jon P<template>
元素,那么您仍然在使用Web组件技术的一部分吗?不,模板字面量不是“存储库”,它们是js语法。您可以使用普通字符串字面量实现完全相同的效果,或者从其他地方加载/生成字符串。 - Bergi