forked from SergeiDudyuk/bitrix-base-project
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathVueInvoker.js
73 lines (57 loc) · 1.67 KB
/
VueInvoker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import Vue from 'vue'
const defaultOptions = {
vueComponentSelector: '.vue-component',
componentDataAttr: 'data-component',
initialDataAttr: 'data-initial',
}
class VueInvoker {
constructor (options = defaultOptions) {
this.options = options
this.instances = []
}
async prepareComponents (collection) {
this.collection = collection
await this.processComponents(this.collection)
}
async processComponents (options) {
this.options = Object.assign(this.options, options)
const $nodes = document.querySelectorAll(this.options.vueComponentSelector)
for (let $item of $nodes) {
this.renderComponent($item).then()
}
}
async renderComponent ($item) {
let componentData = $item.getAttribute(this.options.initialDataAttr)
if (componentData !== undefined) {
try {
componentData = JSON.parse(componentData)
} catch (e) {
componentData = false
}
}
let componentName = $item.getAttribute(this.options.componentDataAttr)
let component = this.collection[componentName]
if (component === undefined) {
console.error('Missing component in the collection:', componentName)
return Promise.resolve(false)
}
return this.createComponentInstance($item, component, componentData)
}
createComponentInstance (element, component, data) {
return new Promise((resolve) => {
let instance = new Vue({
el: element,
render: (r) => r(component, {
props: {
initial: data
}
}),
mounted () {
resolve()
}
})
this.instances.push(instance)
})
}
}
export let vueInvoker = new VueInvoker()