javascript - ES5 中的可共享组件
问题描述
Vue、React 和 Angular 等现代 javascript 框架支持在 Web 应用程序中跨页面/模块创建可共享组件。使用 HTML + ES5 实现这一目标的最佳方法是什么?任何库或框架?我正在使用不支持 ES6 的遗留代码
解决方案
您可以从 JS 中创建 HTML 元素,并带上一个.css
文件用于样式设置或使用 JS 设置样式。然后您只需将其导入到您的 HTML 中,如下所示:
<script src="yourcomponent/index.js"></script>
您还可以使用 acdn
来部署您的组件。
组件中的示例index.js
:
function createRoot() {
const rootElement = document.createElement("div");
document.body.appendChild(rootElement);
return rootElement;
}
function createComponent(root = createRoot(), elementType, className) {
const componentWrapper = document.createElement(elementType);
componentWrapper.setAttribute("class", className);
return componentWrapper;
}
// usage
// you can pass root or not
const component = createComponent(document.getElementById("root"), "div", "my-component-wrapper");
然后,您可以将额外的 DOM 节点附加到它或应用功能。所有这些都可以与您的脚本一起使用。
希望这可以作为灵感:)
推荐阅读
- sql - 用户操作之间的平均时间(SQL 和 pandas)
- html - h5和字体平滑度/抗锯齿/粗体的奇怪问题
- jsf - 如何向 JSF 申请提交可填写的 PDF 表格
- c++ - 如何在 C++ 中输入测试用例的数量?
- c++ - cURL 释放模式参数无效
- odoo-13 - 如何在 odoo13 中仅使用 odoo 库环境之外的 javascript 打开电子邮件编写器之类的操作?
- wordpress - wp媒体上传器在小屏幕上没有响应
- python - 将“python”更改为指向 virtualenv 中的 python2.7
- php - 如何在第一个结果中跳出 foreach 循环并从第二个结果继续循环
- javascript - ER_parse_error:您的 SQL 语法有错误;输入数据失败 -Nodejs -mysql -express