3.9 KiB
3.9 KiB
MathPage 公共工具
这个目录包含了数学页面的公共工具和复用代码。
mathPageMixin.ts
提供了所有数学页面的公共功能,包括:
- Canvas 初始化
- 分享功能(小程序分享、朋友圈分享)
- 导出打印功能
- 页面信息初始化
使用方法
import { getMathPageCommonMethods } from '../common/mathPageMixin';
import YourDrawService from '../service/yourDrawService';
// 获取公共方法,传入页面路径
const commonMethods = getMathPageCommonMethods({
pagePath: 'yourPage/yourPage', // 相对于 mathPages 目录的路径
});
Page({
// Canvas 相关属性
canvas: null as Canvas | null,
ctx: null as RenderingContext | null,
boxHeight: 0,
boxWidth: 0,
drawService: null as YourDrawService | null,
// 页面数据(包含公共数据)
data: {
functionId: '',
pageTitle: '',
subTitle: '',
hasContent: false,
showShareDialog: false,
boxWidth: 0,
boxHeight: 0,
// ... 其他页面特定的数据
},
onLoad(options: { id?: string }) {
const functionId = options.id || 'your-function-id';
// 使用公共方法初始化页面信息
this.initPageInfo(functionId, '默认标题');
},
onReady() {
// 使用公共方法初始化 Canvas
this.initCanvas({
createDrawService: (canvas, ctx, options) => {
return new YourDrawService(canvas, ctx, options);
},
drawServiceOptions: {
// 传递给绘制服务的选项
},
onCanvasReady: () => {
// Canvas 初始化完成后的回调
this.onRandom(); // 或其他初始化操作
},
});
},
// 实现页面特定的绘制逻辑
async drawCanvas() {
if (!this.ctx || !this.drawService || !this.yourData) {
return;
}
try {
await this.drawService.draw(this.yourData);
this.setData({ hasContent: true });
} catch (error) {
console.error('绘制失败:', error);
this.setData({ hasContent: false });
}
},
// 页面特定的方法
onRandom() {
// 生成数据逻辑
this.drawCanvas();
},
// ========== 使用公共方法 ==========
initCanvas: commonMethods.initCanvas,
exportToPrint: commonMethods.exportToPrint,
onShareAppMessage: commonMethods.onShareAppMessage,
onShareTimeline: commonMethods.onShareTimeline,
onCloseShareDialog: commonMethods.onCloseShareDialog,
onShareSuccess: commonMethods.onShareSuccess,
initPageInfo: commonMethods.initPageInfo,
});
提供的公共方法
-
initCanvas(options) - 初始化 Canvas
createDrawService: 创建绘制服务的工厂函数drawServiceOptions: 传递给绘制服务的选项onCanvasReady: Canvas 初始化完成后的回调
-
drawCanvas() - 绘制 Canvas 内容(需要子类实现)
-
exportToPrint() - 导出打印
-
onShareAppMessage() - 小程序分享
-
onShareTimeline() - 朋友圈分享
-
onCloseShareDialog() - 关闭分享引导弹窗
-
onShareSuccess() - 分享成功回调
-
initPageInfo(functionId, defaultTitle) - 初始化页面信息
- 从
MATH_FUNCTION_TYPES中获取标题和描述 - 设置导航栏标题
- 从
优势
- ✅ 代码复用: 消除了重复代码
- ✅ 类型安全: 完整的 TypeScript 类型支持
- ✅ 易于维护: 公共功能集中管理
- ✅ 灵活扩展: 每个页面可以重写特定方法
迁移指南
从旧代码迁移到使用 mixin:
- 导入公共方法
- 移除重复的方法(exportToPrint、分享相关等)
- 使用
initCanvas替代原有的 Canvas 初始化代码 - 使用
initPageInfo替代页面信息初始化代码 - 将公共方法添加到 Page 配置中