1b7143fa33a5919c0c7e67111703b9014d7b76d5234a1ee0e09eba6935509152b5273547b7f86a753b32dfb9ec5283e7c6e875c763ee3a7118a8e812f1088e 2.1 KB

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