1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| let snabbdom = require("snabbdom"); let patch = snabbdom.init([ require("snabbdom/modules/class").default, require("snabbdom/modules/props").default, require("snabbdom/modules/style").default, require("snabbdom/modules/eventlisteners").default, ]); let h = require("snabbdom/h").default;
let container = document.getElementById("container");
let data = new Array(10) .fill(0) .map((_, i) => i) .map((index) => ({ index, content: "-" + index + "--" + randomString(20) + "_lxcan", time: Date.now(), }));
let vnode = initVnode(data);
patch(container, vnode);
function initVnode(data) { return h( "div.wrap", { style: { width: "600px", margin: "50px auto", padding: "20px", border: "1px solid #000", }, }, [ h("header.header-wrap", [ h( "button", { style: { "margin-right": "10px" }, on: { click: [changeSort, "order"] }, }, "顺序排列" ), h( "button", { style: { "margin-right": "10px" }, on: { click: [changeSort, "reorder"] }, }, "倒序排列" ), h( "button", { style: { "margin-right": "10px" }, on: { click: [changeSort, "random"] }, }, "随机排列" ), h("button", { on: { click: addItem } }, "添加1项"), ]), h("table", [ h("tr", [h("th", "序号"), h("th", "内容"), h("th", "添加时间")]), h("tbody", data.map(getTrVnode)), ]), ] ); }
function getTrVnode(item) { return h("tr", [ h("td", item.index), h("td", item.content), h("td", item.time), ]); }
function changeSort(type) { if (type === "order") { data.sort((a, b) => a.index - b.index); } else if (type === "reorder") { data.sort((a, b) => b.index - a.index); } else if (type === "random") { data.sort(() => (Math.random() > 0.5 ? -1 : 1)); } render(data); }
function addItem() { const total = data.length; const item = { index: total, content: "-" + total + "--" + randomString(20) + "_lxcan", time: Date.now(), }; data.unshift(item); render(data); }
function render(data) { vnode = patch(vnode, initVnode(data)); }
function randomString(len) { len = len || 32; var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; var maxPos = $chars.length; var pwd = ""; for (i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; }
|