mixins.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // 保存原生的 Page 函数
  2. const originPage = Page
  3. Page = (options) => {
  4. const mixins = options.mixins
  5. // mixins 必须为数组
  6. if (Array.isArray(mixins)) {
  7. delete options.mixins
  8. // mixins 注入并执行相应逻辑
  9. options = 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, options) {
  18. if (!Object.entries) {
  19. Object.entries = function (obj) {
  20. var ownProps = Object.keys(obj),
  21. i = ownProps.length,
  22. resArray = new Array(i); // preallocate the Array
  23. while (i--)
  24. resArray[i] = [ownProps[i], obj[ownProps[i]]];
  25. return resArray;
  26. };
  27. }
  28. mixins.forEach((mixin) => {
  29. if (Object.prototype.toString.call(mixin) !== '[object Object]') {
  30. throw new Error('mixin 类型必须为对象!')
  31. }
  32. // 遍历 mixin 里面的所有属性
  33. for (let [key, value] of Object.entries(mixin)) {
  34. if (originProperties.includes(key)) {
  35. // 内置对象属性混入
  36. options[key] = { ...value, ...options[key] }
  37. } else if (originMethods.includes(key)) {
  38. // 内置方法属性混入,优先执行混入的部分
  39. const originFunc = options[key]
  40. options[key] = function (...args) {
  41. value.call(this, ...args)
  42. return originFunc && originFunc.call(this, ...args)
  43. }
  44. } else {
  45. // 自定义方法混入
  46. options = { ...mixin, ...options }
  47. }
  48. }
  49. })
  50. return options
  51. }