1 |
|
2 |
|
3 | import { hasOwn } from 'shared/util'
|
4 | import { warn, hasSymbol } from '../util/index'
|
5 | import { defineReactive, toggleObserving } from '../observer/index'
|
6 |
|
7 | export function initProvide (vm: Component) {
|
8 | const provide = vm.$options.provide
|
9 | if (provide) {
|
10 | vm._provided = typeof provide === 'function'
|
11 | ? provide.call(vm)
|
12 | : provide
|
13 | }
|
14 | }
|
15 |
|
16 | export function initInjections (vm: Component) {
|
17 | const result = resolveInject(vm.$options.inject, vm)
|
18 | if (result) {
|
19 | toggleObserving(false)
|
20 | Object.keys(result).forEach(key => {
|
21 |
|
22 | if (process.env.NODE_ENV !== 'production') {
|
23 | defineReactive(vm, key, result[key], () => {
|
24 | warn(
|
25 | `Avoid mutating an injected value directly since the changes will be ` +
|
26 | `overwritten whenever the provided component re-renders. ` +
|
27 | `injection being mutated: "${key}"`,
|
28 | vm
|
29 | )
|
30 | })
|
31 | } else {
|
32 | defineReactive(vm, key, result[key])
|
33 | }
|
34 | })
|
35 | toggleObserving(true)
|
36 | }
|
37 | }
|
38 |
|
39 | export function resolveInject (inject: any, vm: Component): ?Object {
|
40 | if (inject) {
|
41 |
|
42 | const result = Object.create(null)
|
43 | const keys = hasSymbol
|
44 | ? Reflect.ownKeys(inject)
|
45 | : Object.keys(inject)
|
46 |
|
47 | for (let i = 0; i < keys.length; i++) {
|
48 | const key = keys[i]
|
49 |
|
50 | if (key === '__ob__') continue
|
51 | const provideKey = inject[key].from
|
52 | let source = vm
|
53 | while (source) {
|
54 | if (source._provided && hasOwn(source._provided, provideKey)) {
|
55 | result[key] = source._provided[provideKey]
|
56 | break
|
57 | }
|
58 | source = source.$parent
|
59 | }
|
60 | if (!source) {
|
61 | if ('default' in inject[key]) {
|
62 | const provideDefault = inject[key].default
|
63 | result[key] = typeof provideDefault === 'function'
|
64 | ? provideDefault.call(vm)
|
65 | : provideDefault
|
66 | } else if (process.env.NODE_ENV !== 'production') {
|
67 | warn(`Injection "${key}" not found`, vm)
|
68 | }
|
69 | }
|
70 | }
|
71 | return result
|
72 | }
|
73 | }
|