自定义属性
约 728 字大约 2 分钟
...
2026-09-29
说明
自定义属性 用于给元素属性面板新增参数项。
参数值保存在元素 options 中,随模板 json 一起保存。例如: 全局 id、业务标识、自定义样式等等。
主要使用 init hook:
Config.registerItems([...]):注册属性项(控件)Config.<type>.supportOptions / tabs:把属性项挂到指定元素的属性面板
开源参考:plugin-scale(给 text/image 元素加"缩放"属性)。
编写属性项
属性项是一个类,核心方法:name、createTarget(面板控件 DOM)、getValue、setValue、destroy。
globalId.ts
class GlobalIdOption {
name = 'globalId'; // 对应元素 options 的键名, 需全局唯一
target: any = null;
// 创建属性面板 DOM(input 添加 auto-submit 类, 修改后自动保存并刷新)
createTarget(printElement: any, options: any, printElementType: any) {
const el = globalThis.$(
`<div class="hiprint-option-item hiprint-option-item-row">
<div class="hiprint-option-item-label">全局id</div>
<div class="hiprint-option-item-field">
<input type="text" class="auto-submit" placeholder="如: order-001" /> <!-- [!code warning] auto-submit 自动保存 -->
</div>
</div>`,
);
this.target = el;
return this.target;
}
getValue() {
const v = this.target.find('input').val();
return v || undefined;
}
setValue(value: string) {
this.target.find('input').val(value || '');
}
destroy() {
this.target.remove();
}
}
export const GlobalIdOptionFun = () =>
function () {
return new GlobalIdOption();
};编写插件
index.ts
import type { PluginOptions } from 'sv-print';
import { GlobalIdOptionFun } from './globalId';
export default function plugin(config?: any): PluginOptions {
return {
name: 'globalId',
description: '元素自定义属性 全局id',
hooks: [
{
hook: 'init',
name: 'globalId',
priority: 1,
run: ({ Config }) => {
// 1. 注册属性项控件
Config.registerItems([GlobalIdOptionFun()]);
// 2. 挂到 text 元素属性面板(supportOptions + tabs 需同时挂)
Config.text.supportOptions.push({ name: 'globalId', hidden: false });
Config.text.tabs.forEach((tab) => {
if (tab.name === '基础') {
tab.options.push({ name: 'globalId', hidden: false }); // 不加 tabs 则面板不显示
}
});
},
},
],
leastHiprintVersion: '0.1.0',
};
}挂到其他元素
参考 plugin-scale:把 Config.text 换成对应元素配置(如 Config.image),或在 Config.<type>.supportOptions 中按需插入,即可挂到任意元素。
使用
await hiprint.register({ plugins: [plugin({})] });
// 注册后 text 元素属性面板"基础"页签出现"全局id"输入框属性值随元素保存,可通过模板 json / 元素 options 读取:
const template = new hiprint.PrintTemplate({
panel: {
printElements: [
{
options: {
left: 0,
top: 0,
globalId: 'order-001', // 自定义属性随模板保存
},
printElementType: { type: 'text', title: '文本' },
},
],
},
});
// 运行时读取元素的自定义属性 // [!code word:globalId
const globalId = template.printElements[0].options.globalId;如需在打印时按该属性做特殊处理,可配合 beforeGetHtml / beforePrint 等 hook 遍历元素,按 options.globalId 匹配。
版权所有
版权归属:sv-print
