vueComponent.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { defineComponent } from 'vue';
  2. import _ from 'lodash';
  3. export default function(componentClass) {
  4. const comp = {};
  5. const obj = new componentClass();
  6. //data, options, props
  7. const data = {};
  8. for (const prop of Object.getOwnPropertyNames(obj)) {
  9. if (['_options', '_props'].includes(prop)) {//meta props
  10. if (prop === '_options') {
  11. const options = obj[prop];
  12. for (const optName of ['components', 'watch', 'emits']) {
  13. if (options[optName]) {
  14. comp[optName] = options[optName];
  15. }
  16. }
  17. } else if (prop === '_props') {
  18. comp['props'] = obj[prop];
  19. }
  20. } else {//usual prop
  21. data[prop] = obj[prop];
  22. }
  23. }
  24. comp.data = () => _.cloneDeep(data);
  25. //methods
  26. const classProto = Object.getPrototypeOf(obj);
  27. const classMethods = Object.getOwnPropertyNames(classProto);
  28. const methods = {};
  29. const computed = {};
  30. for (const method of classMethods) {
  31. const desc = Object.getOwnPropertyDescriptor(classProto, method);
  32. if (desc.get) {//has getter, computed
  33. computed[method] = {get: desc.get};
  34. if (desc.set)
  35. computed[method].set = desc.set;
  36. } else if ( ['beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'activated',//life cycle hooks
  37. 'deactivated', 'beforeUnmount', 'unmounted', 'errorCaptured', 'renderTracked', 'renderTriggered',//life cycle hooks
  38. 'setup'].includes(method) ) {
  39. comp[method] = obj[method];
  40. } else if (method !== 'constructor') {//usual
  41. methods[method] = obj[method];
  42. }
  43. }
  44. comp.methods = methods;
  45. comp.computed = computed;
  46. //console.log(comp);
  47. return defineComponent(comp);
  48. }