vue模板编译器
import {ASTElement, compile} from 'vue-template-compiler';
import {TableColumnDesc} from "@/components/table/base-table/type.ts";
export const codeAdapter = function (code: string): {
tableCode: string;
columns: TableColumnDesc[];
} {
const result:{
tableCode: string;
columns: TableColumnDesc[];
} = {
tableCode: "",
columns: [],
};
const {ast} = compile(code);
console.log(ast);
// table
result.tableCode = tableCode(ast);
result.columns = columnCode(ast);
return result;
};
function tableCode(ast: ASTElement) {
let code = `<BaseTable
`;
const attrsMap = ast.attrsMap;
const attrs = ["ref", ":data", "v-loading", "rowKey", ":summary-method", ":summaryMethod", "@current-change", "@currentChange",];
attrs.forEach(attr => {
if (attrsMap[attr]) {
code += ` ${attr}="${attrsMap[attr]}"
`;
}
});
const boolAttrs = [
":highlight-current-row", ":highlightCurrentRow", "highlight-current-row", "highlightCurrentRow",
":show-summary", ":showSummary", "show-summary", "showSummary",
"border", ":border",
"stripe", ":stripe",
];
boolAttrs.forEach(attr => {
if (Object.hasOwn(attrsMap, attr)) {
code += `${attr}
`;
}
});
code += "/>";
return code;
}
function columnCode(ast: ASTElement): TableColumnDesc[] {
return ast.children.filter(i => i.tag == 'el-table-column' || i.tag == 'jh-table-column').map(item => {
const attrsMap: Record<string, string> = item.attrsMap;
let {
label,
type,
width,
prop,
fixed,
align,
} = attrsMap;
if (type === "index") {
return {
type: "index",
label: label || "序号",
}
}
if (type == "selection") {
return {
type: "index",
label: label || "序号",
}
}
const result: TableColumnDesc = {};
if (type) {
result.type = type;
}
if (label) {
result.label = label;
}
if (fixed) {
result.fixed = fixed;
}
if (typeof prop === "string") {
result.name = prop;
}
else {
if (attrsMap[":propAttr"]) {
result.name = eval(attrsMap[":propAttr"])[0];
}
}
if (typeof align === "string" && align !== "center") {
result.align = align;
}
if (attrsMap[":width"]) {
result.width = attrsMap[":width"];
}
return result;
});
}