模板说明
打印模板实际就是一个 json 数据.
格式说明: .
数据填充: 根据模板数据中的字段名(field)填充数据. .
比如: 有一个文本元素 字段名(field) 为 "name". 则在数据填充时, 可以使用 "name" 填充该文本元素.
const printData = { name:'张三' };
// 模板对象
let template = { panesl: [{}]};
let printTemplate = new hiprint.PrintTemplate({ template:template });
// 浏览器 打印
printTemplate.print(printData);
// 浏览器 批量打印
printTemplate.print([printData,printData,printData]);模板导入
一般情况,我们的模板是从服务端获取的.
- 可以先有一个模板列表展示,点击再编辑 (本地缓存=>设计器获取, 或传递id再获取模板json).
- 也可以在自己的页面传id,从服务器获取模板.
template 可以是 模板json 也可以是 模板对象的参数 .
<template>
  <div style="width: 100vw; height: 97vh;">
    <Designer v-if="showDesigner" :template="template" @onDesigned="onDesigned" />
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import axios from 'axios';
import { Designer } from '@sv-print/vue3';
// 定义一个变量是否显示设计器, 如果想直接显示,可以看 onDesigned 方法
let showDesigner = ref(false);
// 模板json, 从服务器获取后
let template = ref({});
// 服务器获取,再显示设计器
const loadTemplate = async () => {
  // 模板json, 从服务器获取后, 赋值给 template.value
  const res = await axios.get('/template/get?id=123');
  template.value = res.data.template;
  showDesigner.value = true;
}
loadTemplate();
// 设计器渲染完成后, 更新模板对象
const onDesigned = (e) => {
  console.log('onDesigned');
  console.log(e);
  const { designerUtils } = e.detail;
  console.log(designerUtils);
  // 更新当前 设计器模
  designerUtils.printTemplate.update(template.value)
  // 更新设计时的 打印数据
  designerUtils.printData =  { name:'张三' };
};
</script>模板导出
- 使用 events onSave.
- 自己写按钮, 调用 designerUtils 的相关 API 导出模板.
<template>
  <div style="width: 100vw; height: 97vh;">
    <button @click="exportTemplate">导出模板</button>
    <Designer :template="template" :events="events" @onDesigned="onDesigned" />
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { Designer } from '@sv-print/vue3';
// 定义设计器工具类
const utils = ref(null);
const onDesigned = (e) => {
  console.log('onDesigned');
  console.log(e);
  const { designerUtils } = e.detail;
  console.log(designerUtils);
  utils.value = designerUtils;
};
// 方式1: 设计器事件获取模板
const events = ref({
  // 保存模板
  onSave: (key, data) => {
    console.log('保存模板', key, data);
    return true; // 返回 true 阻止冒泡
  },
});
// 方式2: 自己写按钮导出模板
const exportTemplate = () => {
  if (!utils.value) {
    console.log('请先设计模板');
    return;
  }
  const template = utils.value.printTemplate.getJson();
  console.log(template);
}
</script>