forked from vuejs/vue-test-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-slots.js
60 lines (55 loc) · 1.87 KB
/
add-slots.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
// @flow
import { compileToFunctions } from 'vue-template-compiler'
import { throwError } from 'shared/util'
import { validateSlots } from './validate-slots'
// see https://github.com/vuejs/vue-test-utils/pull/274
function createVNodes (vm: Component, slotValue: string) {
const compiledResult = compileToFunctions(`<div>${slotValue}{{ }}</div>`)
const _staticRenderFns = vm._renderProxy.$options.staticRenderFns
vm._renderProxy.$options.staticRenderFns = compiledResult.staticRenderFns
const elem = compiledResult.render.call(vm._renderProxy, vm.$createElement).children
vm._renderProxy.$options.staticRenderFns = _staticRenderFns
return elem
}
function validateEnvironment (): void {
if (!compileToFunctions) {
throwError('vueTemplateCompiler is undefined, you must pass components explicitly if vue-template-compiler is undefined')
}
if (typeof window === 'undefined') {
throwError('the slots string option does not support strings in server-test-uitls.')
}
}
function addSlotToVm (vm: Component, slotName: string, slotValue: SlotValue): void {
let elem
if (typeof slotValue === 'string') {
validateEnvironment()
elem = createVNodes(vm, slotValue)
} else {
elem = vm.$createElement(slotValue)
}
if (Array.isArray(elem)) {
if (Array.isArray(vm.$slots[slotName])) {
vm.$slots[slotName] = [...vm.$slots[slotName], ...elem]
} else {
vm.$slots[slotName] = [...elem]
}
} else {
if (Array.isArray(vm.$slots[slotName])) {
vm.$slots[slotName].push(elem)
} else {
vm.$slots[slotName] = [elem]
}
}
}
export function addSlots (vm: Component, slots: Object): void {
validateSlots(slots)
Object.keys(slots).forEach((key) => {
if (Array.isArray(slots[key])) {
slots[key].forEach((slotValue) => {
addSlotToVm(vm, key, slotValue)
})
} else {
addSlotToVm(vm, key, slots[key])
}
})
}