文件

快速開始

安裝 RenderJS,並渲染第一個鏈式 DOM 元素或 RJS 模板。

前置需求

安裝

透過 npm 安裝

npm i @pardnchiu/renderjs

透過 CDN 引入

<!-- 2.0.0 版本以上 -->
<script src="https://cdn.jsdelivr.net/npm/@pardnchiu/renderjs@[VERSION]/dist/RenderJS.js"></script>

<!-- 1.5.2 版本以下(舊名 PDRenderKit) -->
<script src="https://cdn.jsdelivr.net/npm/pdrenderkit@[VERSION]/dist/PDRenderKit.js"></script>

第一次渲染:鏈式 DOM 建構

"tag.class#id"._(attrs, children) 依標籤選擇器字串建立真實 DOM 元素,自動處理 SVG 命名空間與 input/textarea 型別解析。

document.body._child(
    "section#test"._([
        "button"._({
            style: {
                width: "10rem",
                height: "2rem",
                backgroundColor: "steelblue",
                color: "#fff"
            }
        }, [
            "span"._("test"),
            " button"
        ])._click(function () {
            alert("test");
        }),
        "img"._({ lazyload: "https://xxxxxx" }),
        "input@email type"._()
    ])
);

// 啟用 SVG 內嵌與圖片延遲載入監聽器
_Listener({
    svg: true,
    lazyload: true
});

元素查詢

"test".$;          // document.getElementById("test")
"div.test".$;       // document.querySelector("div.test")
"div.test".$all;    // [...document.querySelectorAll("div.test")]

第一個 RJS 模板

RJS 只渲染一次(不做 vDOM 比對),下一次渲染需透過 renew() 手動觸發。指令解析流程詳見 核心概念

const app = "#app".RJS({
    data: {
        // 定義資料
    },
    event: {
        // 定義事件方法
    },
    when: {
        before_render: function () {
            // 渲染前執行,return false 可中止渲染
        },
        rendered: function () {
            // 渲染完成後執行
        }
    }
});

// 更新:僅需傳入要更新的項目,未提及的項目維持初始值
app.renew({
    data: { /* ... */ },
    event: { /* ... */ },
    when: { /* ... */ }
});

網路請求

"url".$req(body) 是一個支援 JSON/FormData、自動解析回應的 fetch 封裝——完整的 URLString 擴充列表見 API 參考

const result = await "/api/x".$req({
    method: "POST",
    json: { key: "value" },
    header: { "X-Token": "..." }
});

下一步

EN