在本文中,我将讨论如何使用 fusor 库开发可重用的 web 组件 以及这样做的好处。
这些组件可以组合成成熟的 web 应用程序,与使用 react、angular、vue、solid、svelte 等创建的应用程序相同。
fusor api 仅由两个 主要函数组成:
加上一些很少使用的功能,例如:
你不需要了解这个特殊物体的任何信息。
import { getelement } from "@fusorjs/dom"; const count = 0; // create via jsx const message = <div>seconds {count} elapsed</div>; document.body.append(getelement(message)); // get
我们使用了 create 和 get api 函数。
import { div } from "@fusorjs/dom/html"; const message = div("seconds ", count, " elapsed"); // create
import { getelement, update } from "@fusorjs/dom"; let count = 0; const message = <div>seconds {() => count} elapsed</div>; // create document.body.append(getelement(message)); // get setinterval(() => { count += 1; update(message); // update }, 1000);
我们使用了update api 函数。它以递归方式更新 dom 元素及其所有子元素。它从函数结果中检索新值,使它们变得动态. 子项、属性和属性都可以是动态的。
<div class={() => (toggle ? "on" : "off")} />
不同时,才会发生 dom 更新。 设置参数
<div style="padding:1em" />
和属性。要指定它们的类型,您可以在它们的名称中添加 _a 或 _p 后缀:
<div name1_a="attribute" name2_p="property" />
,您必须始终使用 _e 后缀:
<div click_e={() => "event handler"} />
以确保完整的w3c标准兼容性:
<div click_e_capture_once={() => "event handler"} />
这是一个计数按钮组件的示例:
import { getelement, update } from "@fusorjs/dom"; const countingbutton = (props) => { let count = props.count ?? 0; // init state const self = ( <button click_e={() => { count += 1; update(self); }} > clicked {() => count} times </button> ); return self; }; const app = () => ( <div style="padding:1em"> <p>three counting buttons</p> <countingbutton /> <countingbutton count={22} /> <countingbutton count={333} /> </div> ); document.body.append(getelement(app()));
,而不影响应用程序的其余部分。 一旦你完全理解了上述组件的工作原理,你就可以用稍微
更短的方式重写它,同时达到相同的结果:
const countingbutton = ({ count = 0 }) => ( <button click_e={(event, self) => { count += 1; update(self); }} > clicked {() => count} times </button> );
再一次,如果您理解上面的示例,请查看同一组件的
最短版本:
const countingbutton = ({ count = 0 }) => ( <button click_e_update={() => (count += 1)}> clicked {() => count} times </button> );
生命周期
它仅由四个阶段组成:
import { getElement, update } from "@fusorjs/dom"; const IntervalCounter = ({ count = 0 }) => { console.log("1. Create the component"); return ( <div mount={(self) => { console.log("2. Connect to the DOM"); const timerId = setInterval(() => { count++; update(self); console.log("3. Update the DOM"); }, 1000); return () => { clearInterval(timerId); console.log("4. Disconnect from the DOM"); }; }} > Since mounted {() => count} seconds elapsed </div> ); }; const instance = <IntervalCounter />; const element = getElement(instance); document.body.append(element); setTimeout(() => element.remove(), 15000);
我们完全控制生命周期的这四个阶段。这让我们可以使用自定义的
异步或并发方法来创建、更新和比较组件,并考虑不同的策略和动画帧。 教程到此结束
api 函数。然而,它在需要时也提供了很多控制和灵活性。 所以,回答标题中的问题,fusor 是一个小型 javascript 库,不是框架,但它可以达到与其他框架相同的结果。
开始编码
另外,请查看 svg 模拟时钟示例。
这是一个真实世界的应用程序。
样板入门项目: