1 | class componentFactory {
|
2 | constructor() {
|
3 | this.components = {}
|
4 | this.appComponents = {}
|
5 | }
|
6 |
|
7 | registerComponent(name, component) {
|
8 | if (this.components[name]) {
|
9 | throw `组件existed. name: ${name}`
|
10 | }
|
11 | this.components[name] = component
|
12 | }
|
13 |
|
14 | registerAppComponent(appName, componentName, component) {
|
15 | this.appComponents[appName] = this.appComponents[appName] || {}
|
16 | this.appComponents[appName].components = this.appComponents[appName].components || {}
|
17 | if (this.appComponents[appName].components[componentName])
|
18 | throw `组件existed. app:${appName}, name: ${componentName}`
|
19 | this.appComponents[appName].components[componentName] = component
|
20 | }
|
21 |
|
22 | registerComponents(components) {
|
23 | if (!components || components.length == 0)
|
24 | return
|
25 | components.forEach(c => this.registerComponent(c.name, c.component))
|
26 | }
|
27 |
|
28 | getComponent(appName, name) {
|
29 | if (!name)
|
30 | throw 'component name can not null'
|
31 |
|
32 | if (name.substring(0, 2) == '::') {
|
33 | if(name.substr(2))
|
34 | return name.substr(2)
|
35 | else
|
36 | throw `没有组件. name: ::`
|
37 | }
|
38 |
|
39 | const nameSegs = name.split('.'),
|
40 | firstSeg = nameSegs[0]
|
41 |
|
42 | if (this.appComponents && this.appComponents[appName] && this.appComponents[appName].components && this.appComponents[appName].components[firstSeg]) {
|
43 | var com = this.appComponents[appName].components[name]
|
44 |
|
45 | if (com && nameSegs.length > 1) {
|
46 | com = this.findChild(com, nameSegs)
|
47 | }
|
48 |
|
49 | if (com) return com
|
50 |
|
51 | }
|
52 |
|
53 | var component = this.components[firstSeg]
|
54 |
|
55 | if (component && nameSegs.length > 1) {
|
56 | component = this.findChild(component, nameSegs)
|
57 | }
|
58 |
|
59 | if (!component) {
|
60 | throw `没有组件. name: ${name}`
|
61 | }
|
62 |
|
63 | return component
|
64 | }
|
65 |
|
66 | findChild(component, nameSegs) {
|
67 | for (let s of nameSegs.slice(1)) {
|
68 | if (!component[s]) {
|
69 | component = undefined
|
70 | return
|
71 | }
|
72 |
|
73 | component = component[s]
|
74 | }
|
75 | return component
|
76 |
|
77 | }
|
78 |
|
79 |
|
80 | }
|
81 |
|
82 | const instance = new componentFactory()
|
83 |
|
84 | export default instance |
\ | No newline at end of file |