mixins_core.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // 保存原生的 Page 函数
  2. const originPage = Page
  3. Page = (options: any) => {
  4. const mixins = options.mixins
  5. // mixins 必须为数组
  6. if (Array.isArray(mixins)) {
  7. delete options.mixins
  8. // mixins 注入并执行相应逻辑
  9. merge(mixins, options)
  10. }
  11. // 释放原生 Page 函数
  12. originPage(options)
  13. }
  14. // 定义小程序内置的属性/方法
  15. const originProperties = ['data', 'properties', 'options']
  16. const originMethods = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll', 'onTabItemTap']
  17. function merge(mixins: any[], options: any) {
  18. mixins.forEach((mixin) => {
  19. if (Object.prototype.toString.call(mixin) !== '[object Object]') {
  20. throw new Error('mixin 类型必须为对象!')
  21. }
  22. // 遍历 mixin 里面的所有属性
  23. for (let [key, value] of Object.entries(mixin)) {
  24. if (originProperties.includes(key)) {
  25. // 内置对象属性混入
  26. options[key] = { ...(<any>value), ...options[key] }
  27. } else if (originMethods.includes(key)) {
  28. // 内置方法属性混入,优先执行混入的部分
  29. const originFunc = options[key]
  30. options[key] = function (...args: any) {
  31. (<any>value).call(this, ...args)
  32. return originFunc && originFunc.call(this, ...args)
  33. }
  34. } else {
  35. // 自定义方法混入
  36. options = { ...mixin, ...options }
  37. }
  38. }
  39. })
  40. }