Web Components学习(2)-语法
创始人
2024-05-31 22:44:01

一、Web Components 对 Vue 的影响

尤雨溪在创建 Vue 的时候大量参考了 Web Components 的语法,下面写个简单示例。

首先写个 Vue 组件 my-span.vue:


这是很标准的 Vue 组件,不过非常遗憾的是 HTML 文件并不能有效的利用这个 vue 文件,如果想让它能够正确运行,还需要下载 node、webpack、vue-loader 将其打包,而且它只能在 Vue 的项目中使用,也就是必须依赖 Vue 的安装包。如果在 React、Angular 甚至 jQuery 项目中,这个组件就不能用了。

但是以前只需要将它稍稍修改一下,它就会变成 Web Components 文件,能够直接在浏览器中运行。

只需要修改

使用 HTML Imports 在 HTML 页面中引入组件:




Document



但是现在 HTML Imports 已废弃(被 ES Modules 的代替),所以不能使用这种方式了。

如果还想要以独立模块的方式引入,那么就要通过 JS 生成 HTML 和 CSS:

// my-span.js
class MySpan extends HTMLElement {constructor() {super()this.render()}// 生成 HTML 和 CSSrender() {const shadow = this.attachShadow({ mode: 'open' })const dom = document.createElement('span')const style = document.createElement('style')dom.textContent = 'my-span'style.textContent = `span {color: purple;}`shadow.appendChild(style)shadow.appendChild(dom)}
}// 注册组件
customElements.define('my-span', MySpan)



Document



注意:使用 ES Modules 和 HTML Imports 一样,都要开启一个 Web 服务,直接打开 HTML 文件,会以文件协议(file://)的方式打开,控制台会报跨域错误。可以使用 vscode 的 Live Server 插件打开 HTML。或者不使用 ES Modules:

也可以提前在 HTML 页面中通过