snabbdom源碼解析(二) h函數

介紹

這裏是 typescript 的語法,定義了一系列的重載方法。
h 函數主要根據傳進來的參數,返回一個 vnode 對象

代碼

代碼位置 : ./src/h.ts

/**
 * 根據選擇器 ,數據 ,創建 vnode
 */
export function h(sel: string): VNode;
export function h(sel: string, data: VNodeData): VNode;
export function h(sel: string, children: VNodeChildren): VNode;
export function h(sel: string, data: VNodeData, children: VNodeChildren): VNode;
export function h(sel: any, b?: any, c?: any): VNode {
    var data: VNodeData = {},
        children: any,
        text: any,
        i: number;

    /**
     * 處理參數
     */
    if (c !== undefined) {
        // 三個參數的情況  sel , data , children | text
        data = b;
        if (is.array(c)) {
            children = c;
        } else if (is.primitive(c)) {
            text = c;
        } else if (c && c.sel) {
            children = [c];
        }
    } else if (b !== undefined) {
        // 兩個參數的情況 : sel , children | text
        // 兩個參數的情況 : sel , data
        if (is.array(b)) {
            children = b;
        } else if (is.primitive(b)) {
            text = b;
        } else if (b && b.sel) {
            children = [b];
        } else {
            data = b;
        }
    }

    if (children !== undefined) {
        for (i = 0; i < children.length; ++i) {
            // 如果children是文本或數字 ,則創建文本節點
            if (is.primitive(children[i]))
                children[i] = vnode(
                    undefined,
                    undefined,
                    undefined,
                    children[i],
                    undefined
                );
        }
    }

    // 處理svg
    if (
        sel[0] === 's' &&
        sel[1] === 'v' &&
        sel[2] === 'g' &&
        (sel.length === 3 || sel[3] === '.' || sel[3] === '#')
    ) {
        // 增加 namespace
        addNS(data, children, sel);
    }
    // 生成 vnoe
    return vnode(sel, data, children, text, undefined);
}
export default h;

其他

h 函數比較簡單,主要是提供一個方便的工具函數,方便創建 vnode 對象

:::tip

詳細瞭解 vnode 對象 ,請查看 vnode

:::

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章