/
mixin.ts
243 lines (222 loc) · 6.18 KB
/
mixin.ts
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import type { VueConstructor } from 'vue'
import {
ComponentInstance,
SetupContext,
SetupFunction,
Data,
} from './component'
import { isRef, isReactive, toRefs, isRaw } from './reactivity'
import {
isPlainObject,
assert,
proxy,
warn,
isFunction,
isObject,
def,
isArray,
} from './utils'
import { ref } from './apis'
import vmStateManager from './utils/vmStateManager'
import {
updateTemplateRef,
activateCurrentInstance,
resolveScopedSlots,
asVmProperty,
} from './utils/instance'
import { getVueConstructor } from './runtimeContext'
import { createObserver } from './reactivity/reactive'
export function mixin(Vue: VueConstructor) {
Vue.mixin({
beforeCreate: functionApiInit,
mounted(this: ComponentInstance) {
updateTemplateRef(this)
},
updated(this: ComponentInstance) {
updateTemplateRef(this)
},
})
/**
* Vuex init hook, injected into each instances init hooks list.
*/
function functionApiInit(this: ComponentInstance) {
const vm = this
const $options = vm.$options
const { setup, render } = $options
if (render) {
// keep currentInstance accessible for createElement
$options.render = function (...args: any): any {
return activateCurrentInstance(vm, () => render.apply(this, args))
}
}
if (!setup) {
return
}
if (typeof setup !== 'function') {
if (__DEV__) {
warn(
'The "setup" option should be a function that returns a object in component definitions.',
vm
)
}
return
}
const { data } = $options
// wrapper the data option, so we can invoke setup before data get resolved
$options.data = function wrappedData() {
initSetup(vm, vm.$props)
return typeof data === 'function'
? (data as (
this: ComponentInstance,
x: ComponentInstance
) => object).call(vm, vm)
: data || {}
}
}
function initSetup(vm: ComponentInstance, props: Record<any, any> = {}) {
const setup = vm.$options.setup!
const ctx = createSetupContext(vm)
// fake reactive for `toRefs(props)`
def(props, '__ob__', createObserver())
// resolve scopedSlots and slots to functions
// @ts-expect-error
resolveScopedSlots(vm, ctx.slots)
let binding: ReturnType<SetupFunction<Data, Data>> | undefined | null
activateCurrentInstance(vm, () => {
// make props to be fake reactive, this is for `toRefs(props)`
binding = setup(props, ctx)
})
if (!binding) return
if (isFunction(binding)) {
// keep typescript happy with the binding type.
const bindingFunc = binding
// keep currentInstance accessible for createElement
vm.$options.render = () => {
// @ts-expect-error
resolveScopedSlots(vm, ctx.slots)
return activateCurrentInstance(vm, () => bindingFunc())
}
return
} else if (isPlainObject(binding)) {
if (isReactive(binding)) {
binding = toRefs(binding) as Data
}
vmStateManager.set(vm, 'rawBindings', binding)
const bindingObj = binding
Object.keys(bindingObj).forEach((name) => {
let bindingValue: any = bindingObj[name]
if (!isRef(bindingValue)) {
if (!isReactive(bindingValue)) {
if (isFunction(bindingValue)) {
bindingValue = bindingValue.bind(vm)
} else if (!isObject(bindingValue)) {
bindingValue = ref(bindingValue)
} else if (hasReactiveArrayChild(bindingValue)) {
// creates a custom reactive properties without make the object explicitly reactive
// NOTE we should try to avoid this, better implementation needed
customReactive(bindingValue)
}
} else if (isArray(bindingValue)) {
bindingValue = ref(bindingValue)
}
}
asVmProperty(vm, name, bindingValue)
})
return
}
if (__DEV__) {
assert(
false,
`"setup" must return a "Object" or a "Function", got "${Object.prototype.toString
.call(binding)
.slice(8, -1)}"`
)
}
}
function customReactive(target: object) {
if (
!isPlainObject(target) ||
isRef(target) ||
isReactive(target) ||
isRaw(target)
)
return
const Vue = getVueConstructor()
const defineReactive = Vue.util.defineReactive
Object.keys(target).forEach((k) => {
const val = target[k]
defineReactive(target, k, val)
if (val) {
customReactive(val)
}
return
})
}
function hasReactiveArrayChild(target: object, visited = new Map()): boolean {
if (visited.has(target)) {
return visited.get(target)
}
visited.set(target, false)
if (Array.isArray(target) && isReactive(target)) {
visited.set(target, true)
return true
}
if (!isPlainObject(target) || isRaw(target)) {
return false
}
return Object.keys(target).some((x) =>
hasReactiveArrayChild(target[x], visited)
)
}
function createSetupContext(
vm: ComponentInstance & { [x: string]: any }
): SetupContext {
const ctx = {
slots: {},
} as SetupContext
const props: Array<string | [string, string]> = [
'root',
'parent',
'refs',
'attrs',
'listeners',
'isServer',
'ssrContext',
]
const methodReturnVoid = ['emit']
props.forEach((key) => {
let targetKey: string
let srcKey: string
if (Array.isArray(key)) {
;[targetKey, srcKey] = key
} else {
targetKey = srcKey = key
}
srcKey = `$${srcKey}`
proxy(ctx, targetKey, {
get: () => vm[srcKey],
set() {
warn(
`Cannot assign to '${targetKey}' because it is a read-only property`,
vm
)
},
})
})
methodReturnVoid.forEach((key) => {
const srcKey = `$${key}`
proxy(ctx, key, {
get() {
return (...args: any[]) => {
const fn: Function = vm[srcKey]
fn.apply(vm, args)
}
},
})
})
if (process.env.NODE_ENV === 'test') {
;(ctx as any)._vm = vm
}
return ctx
}
}