什么是 Web Components ?
Web Components 是一个浏览器原生支持的组件化方案,允许你创建新的自定义、可封装、可重用的HTML 标记。不用加载任何外部模块,直接就可以在浏览器中跑。
Web Components 存在的目的就是希望提供给开发者,能够自定义可重用的、可被浏览器正常解析的标签,让逻辑、样式、标签都封装在一个组件内部,最终用自定义的标签渲染视图。
Vue 的模版系统本身是参考 Web Components 的规范进行了上层的设计,因为 Web Components 拥有:自定义标签、自定义属性、自定义组件的特点。
例如我们想要创建一个自定义的组件:
<my-info
avatar="https://cdn.pixabay.com/photo/2023/02/13/05/58/doodle-7786568__340.png"
name="xiechen"
age="22"
occupation="student">
The infomation of xiechen.
</my-info>
// 需要继承 HTMLElement 类
window.customElements.define("my-info", class extends HTMLElement {
constructor() {
super();
// 这里的 this 指向的就是我们的 my-info 标签本身
this.title = this.textContent;
this.avatar = this.getAttribute("avatar");
this.myName = this.getAttribute("name");
this.age = this.getAttribute("age");
this.occupation = this.getAttribute("occupation");
this.init();
}
init() {
var shdowDOM = this.attachShadow({
mode: "open"
});
shdowDOM.appendChild(this.createDOM());
}
createDOM() {
// 创建需要的 DOM
var oContainer = this.createContainer();
oContainer.appendChild(this.createTitle());
oContainer.appendChild(this.createAvatar());
oContainer.appendChild(this.createName());
oContainer.appendChild(this.createAge());
oContainer.appendChild(this.createOccupation());
return oContainer;
}
createContainer() {
var oContainer = document.createElement("div");
oContainer.className = "my-info-container";
return oContainer;
}
createTitle() {
var oTitle = document.createElement("h1");
oTitle.className = "my-info-title";
oTitle.textContent = this.title;
return oTitle;
}
createAvatar() {
var oImage = document.createElement("img");
oImage.className = "my-info-avatar";
oImage.style.width = "200px";
oImage.src = this.avatar;
return oImage;
}
createName() {
var oName = document.createElement("p");
oName.className = "my-info-name";
oName.textContent = this.myName;
return oName;
}
createAge() {
var oAge = document.createElement("p");
oAge.className = "my-info-age";
oAge.textContent = this.age;
return oAge;
}
createOccupation() {
var oOccupation = document.createElement("p");
oOccupation.className = "my-info-occupation";
oOccupation.textContent = this.occupation;
return oOccupation;
}
}
);