|
| 1 | +var Vue |
| 2 | + |
| 3 | +var internalHooks = [ |
| 4 | + 'created', |
| 5 | + 'ready', |
| 6 | + 'beforeCompile', |
| 7 | + 'compiled', |
| 8 | + 'beforeDestroy', |
| 9 | + 'destroyed', |
| 10 | + 'attached', |
| 11 | + 'detached' |
| 12 | +] |
| 13 | + |
| 14 | +function decorate (Component) { |
| 15 | + var capture = new Component(false) |
| 16 | + var options = {} |
| 17 | + // instance properties are data |
| 18 | + var fields = Object.keys(capture) |
| 19 | + if (fields.length) { |
| 20 | + options.data = function () { |
| 21 | + return clone(capture) |
| 22 | + } |
| 23 | + } |
| 24 | + // prototype props. |
| 25 | + // only need to identify hooks and methods. |
| 26 | + // computed properties just work! |
| 27 | + var proto = Component.prototype |
| 28 | + Object.getOwnPropertyNames(proto).forEach(function (key) { |
| 29 | + if (key === 'constructor') { |
| 30 | + return |
| 31 | + } |
| 32 | + // hooks |
| 33 | + if (internalHooks.indexOf(key) > -1) { |
| 34 | + options[key] = proto[key] |
| 35 | + return |
| 36 | + } |
| 37 | + // methods |
| 38 | + var descriptor = Object.getOwnPropertyDescriptor(proto, key) |
| 39 | + if (typeof descriptor.value === 'function') { |
| 40 | + (options.methods || (options.methods = {}))[key] = descriptor.value |
| 41 | + } |
| 42 | + }) |
| 43 | + // copy static options |
| 44 | + Object.keys(Component).forEach(function (key) { |
| 45 | + options[key] = Component[key] |
| 46 | + }) |
| 47 | + // set options |
| 48 | + var Super = proto.__proto__.constructor |
| 49 | + Component.options = Vue.util.mergeOptions(Super.options, options) |
| 50 | + Component['super'] = Super |
| 51 | + Component.extend = Super.extend |
| 52 | + // asset registers |
| 53 | + Vue.config._assetTypes.forEach(function (type) { |
| 54 | + Component[type] = Super[type] |
| 55 | + }) |
| 56 | +} |
| 57 | + |
| 58 | +function clone (val) { |
| 59 | + if (typeof val !== 'object') { |
| 60 | + return val |
| 61 | + } else if (Array.isArray(val)) { |
| 62 | + return val.map(clone) |
| 63 | + } else { |
| 64 | + var res = {} |
| 65 | + Object.keys(val).forEach(function (key) { |
| 66 | + res[key] = clone(val[key]) |
| 67 | + }) |
| 68 | + return res |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +function install (externalVue) { |
| 73 | + Vue = externalVue |
| 74 | + Vue.componentClass = decorate |
| 75 | +} |
| 76 | + |
| 77 | +module.exports = install |
0 commit comments