mixins.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * mixins 为 Page 增加 mixin 功能
  3. */
  4. const originPage = Page;
  5. const originProperties = ['data', 'properties', 'options'];
  6. const originMethods = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll', 'onTabItemTap'];
  7. function merge (mixins, options) {
  8. mixins.forEach((mixin) => {
  9. if (Object.prototype.toString.call(mixin) !== '[object Object]') {
  10. throw new Error('mixin 类型必须为对象!')
  11. }
  12. for (let [key, value] of Object.entries(mixin)) {
  13. if (originProperties.includes(key)) {
  14. options[key] = { ...value, ...options[key] }
  15. } else if (originMethods.includes(key)) {
  16. const originFunc = options[key];
  17. options[key] = function (...args) {
  18. value.call(this, ...args);
  19. return originFunc && originFunc.call(this, ...args)
  20. }
  21. } else {
  22. options = { ...mixin, ...options }
  23. }
  24. }
  25. });
  26. return options
  27. }
  28. Page = (options) => {
  29. const mixins = options.mixins;
  30. if (Array.isArray(mixins)) {
  31. delete options.mixins;
  32. options = merge(mixins, options)
  33. }
  34. originPage(options)
  35. };