componentProxy.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import { ComponentInternalInstance, Data } from './component'
  2. import { nextTick, queueJob } from './scheduler'
  3. import { instanceWatch } from './apiWatch'
  4. import { EMPTY_OBJ, hasOwn, isGloballyWhitelisted, NOOP } from '@vue/shared'
  5. import {
  6. ReactiveEffect,
  7. UnwrapRef,
  8. toRaw,
  9. shallowReadonly
  10. } from '@vue/reactivity'
  11. import {
  12. ExtractComputedReturns,
  13. ComponentOptionsBase,
  14. ComputedOptions,
  15. MethodOptions,
  16. resolveMergedOptions
  17. } from './componentOptions'
  18. import { normalizePropsOptions } from './componentProps'
  19. import { EmitsOptions, EmitFn } from './componentEmits'
  20. import { Slots } from './componentSlots'
  21. import {
  22. currentRenderingInstance,
  23. markAttrsAccessed
  24. } from './componentRenderUtils'
  25. import { warn } from './warning'
  26. /**
  27. * Custom properties added to component instances in any way and can be accessed through `this`
  28. *
  29. * @example
  30. * Here is an example of adding a property `$router` to every component instance:
  31. * ```ts
  32. * import { createApp } from 'vue'
  33. * import { Router, createRouter } from 'vue-router'
  34. *
  35. * declare module '@vue/runtime-core' {
  36. * interface ComponentCustomProperties {
  37. * $router: Router
  38. * }
  39. * }
  40. *
  41. * // effectively adding the router to every component instance
  42. * const app = createApp({})
  43. * const router = createRouter()
  44. * app.config.globalProperties.$router = router
  45. *
  46. * const vm = app.mount('#app')
  47. * // we can access the router from the instance
  48. * vm.$router.push('/')
  49. * ```
  50. */
  51. export interface ComponentCustomProperties {}
  52. // public properties exposed on the proxy, which is used as the render context
  53. // in templates (as `this` in the render option)
  54. export type ComponentPublicInstance<
  55. P = {}, // props type extracted from props option
  56. B = {}, // raw bindings returned from setup()
  57. D = {}, // return from data()
  58. C extends ComputedOptions = {},
  59. M extends MethodOptions = {},
  60. E extends EmitsOptions = {},
  61. PublicProps = P
  62. > = {
  63. $: ComponentInternalInstance
  64. $data: D
  65. $props: PublicProps
  66. $attrs: Data
  67. $refs: Data
  68. $slots: Slots
  69. $root: ComponentPublicInstance | null
  70. $parent: ComponentPublicInstance | null
  71. $emit: EmitFn<E>
  72. $el: any
  73. $options: ComponentOptionsBase<P, B, D, C, M, E>
  74. $forceUpdate: ReactiveEffect
  75. $nextTick: typeof nextTick
  76. $watch: typeof instanceWatch
  77. } & P &
  78. UnwrapRef<B> &
  79. D &
  80. ExtractComputedReturns<C> &
  81. M &
  82. ComponentCustomProperties
  83. const publicPropertiesMap: Record<
  84. string,
  85. (i: ComponentInternalInstance) => any
  86. > = {
  87. $: i => i,
  88. $el: i => i.vnode.el,
  89. $data: i => i.data,
  90. $props: i => (__DEV__ ? shallowReadonly(i.props) : i.props),
  91. $attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs),
  92. $slots: i => (__DEV__ ? shallowReadonly(i.slots) : i.slots),
  93. $refs: i => (__DEV__ ? shallowReadonly(i.refs) : i.refs),
  94. $parent: i => i.parent && i.parent.proxy,
  95. $root: i => i.root && i.root.proxy,
  96. $emit: i => i.emit,
  97. $options: i => (__FEATURE_OPTIONS__ ? resolveMergedOptions(i) : i.type),
  98. $forceUpdate: i => () => queueJob(i.update),
  99. $nextTick: () => nextTick,
  100. $watch: __FEATURE_OPTIONS__ ? i => instanceWatch.bind(i) : NOOP
  101. }
  102. const enum AccessTypes {
  103. SETUP,
  104. DATA,
  105. PROPS,
  106. CONTEXT,
  107. OTHER
  108. }
  109. export interface ComponentRenderContext {
  110. [key: string]: any
  111. _: ComponentInternalInstance
  112. }
  113. export const PublicInstanceProxyHandlers: ProxyHandler<any> = {
  114. get({ _: instance }: ComponentRenderContext, key: string) {
  115. const {
  116. ctx,
  117. setupState,
  118. data,
  119. props,
  120. accessCache,
  121. type,
  122. appContext
  123. } = instance
  124. // data / props / ctx
  125. // This getter gets called for every property access on the render context
  126. // during render and is a major hotspot. The most expensive part of this
  127. // is the multiple hasOwn() calls. It's much faster to do a simple property
  128. // access on a plain object, so we use an accessCache object (with null
  129. // prototype) to memoize what access type a key corresponds to.
  130. if (key[0] !== '$') {
  131. const n = accessCache![key]
  132. if (n !== undefined) {
  133. switch (n) {
  134. case AccessTypes.SETUP:
  135. return setupState[key]
  136. case AccessTypes.DATA:
  137. return data[key]
  138. case AccessTypes.CONTEXT:
  139. return ctx[key]
  140. case AccessTypes.PROPS:
  141. return props![key]
  142. // default: just fallthrough
  143. }
  144. } else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  145. accessCache![key] = AccessTypes.SETUP
  146. return setupState[key]
  147. } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  148. accessCache![key] = AccessTypes.DATA
  149. return data[key]
  150. } else if (
  151. // only cache other properties when instance has declared (thus stable)
  152. // props
  153. type.props &&
  154. hasOwn(normalizePropsOptions(type.props)[0]!, key)
  155. ) {
  156. accessCache![key] = AccessTypes.PROPS
  157. return props![key]
  158. } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  159. accessCache![key] = AccessTypes.CONTEXT
  160. return ctx[key]
  161. } else {
  162. accessCache![key] = AccessTypes.OTHER
  163. }
  164. }
  165. const publicGetter = publicPropertiesMap[key]
  166. let cssModule, globalProperties
  167. // public $xxx properties
  168. if (publicGetter) {
  169. if (__DEV__ && key === '$attrs') {
  170. markAttrsAccessed()
  171. }
  172. return publicGetter(instance)
  173. } else if (
  174. // css module (injected by vue-loader)
  175. (cssModule = type.__cssModules) &&
  176. (cssModule = cssModule[key])
  177. ) {
  178. return cssModule
  179. } else if (
  180. // global properties
  181. ((globalProperties = appContext.config.globalProperties),
  182. hasOwn(globalProperties, key))
  183. ) {
  184. return globalProperties[key]
  185. } else if (__DEV__ && currentRenderingInstance) {
  186. warn(
  187. `Property ${JSON.stringify(key)} was accessed during render ` +
  188. `but is not defined on instance.`
  189. )
  190. }
  191. },
  192. set(
  193. { _: instance }: ComponentRenderContext,
  194. key: string,
  195. value: any
  196. ): boolean {
  197. const { data, setupState, ctx } = instance
  198. if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  199. setupState[key] = value
  200. } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  201. data[key] = value
  202. } else if (key in instance.props) {
  203. __DEV__ &&
  204. warn(
  205. `Attempting to mutate prop "${key}". Props are readonly.`,
  206. instance
  207. )
  208. return false
  209. }
  210. if (key[0] === '$' && key.slice(1) in instance) {
  211. __DEV__ &&
  212. warn(
  213. `Attempting to mutate public property "${key}". ` +
  214. `Properties starting with $ are reserved and readonly.`,
  215. instance
  216. )
  217. return false
  218. } else {
  219. if (__DEV__ && key in instance.appContext.config.globalProperties) {
  220. Object.defineProperty(ctx, key, {
  221. enumerable: true,
  222. configurable: true,
  223. value
  224. })
  225. } else {
  226. ctx[key] = value
  227. }
  228. }
  229. return true
  230. },
  231. has(
  232. {
  233. _: { data, setupState, accessCache, ctx, type, appContext }
  234. }: ComponentRenderContext,
  235. key: string
  236. ) {
  237. return (
  238. accessCache![key] !== undefined ||
  239. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  240. (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
  241. (type.props && hasOwn(normalizePropsOptions(type.props)[0]!, key)) ||
  242. hasOwn(ctx, key) ||
  243. hasOwn(publicPropertiesMap, key) ||
  244. hasOwn(appContext.config.globalProperties, key)
  245. )
  246. }
  247. }
  248. if (__DEV__ && !__TEST__) {
  249. PublicInstanceProxyHandlers.ownKeys = (target: ComponentRenderContext) => {
  250. warn(
  251. `Avoid app logic that relies on enumerating keys on a component instance. ` +
  252. `The keys will be empty in production mode to avoid performance overhead.`
  253. )
  254. return Reflect.ownKeys(target)
  255. }
  256. }
  257. export const RuntimeCompiledPublicInstanceProxyHandlers = {
  258. ...PublicInstanceProxyHandlers,
  259. get(target: ComponentRenderContext, key: string) {
  260. // fast path for unscopables when using `with` block
  261. if ((key as any) === Symbol.unscopables) {
  262. return
  263. }
  264. return PublicInstanceProxyHandlers.get!(target, key, target)
  265. },
  266. has(_: ComponentRenderContext, key: string) {
  267. return key[0] !== '_' && !isGloballyWhitelisted(key)
  268. }
  269. }
  270. // In dev mode, the proxy target exposes the same properties as seen on `this`
  271. // for easier console inspection. In prod mode it will be an empty object so
  272. // these properties definitions can be skipped.
  273. export function createRenderContext(instance: ComponentInternalInstance) {
  274. const target: Record<string, any> = {}
  275. // expose internal instance for proxy handlers
  276. Object.defineProperty(target, `_`, {
  277. configurable: true,
  278. enumerable: false,
  279. get: () => instance
  280. })
  281. // expose public properties
  282. Object.keys(publicPropertiesMap).forEach(key => {
  283. Object.defineProperty(target, key, {
  284. configurable: true,
  285. enumerable: false,
  286. get: () => publicPropertiesMap[key](instance),
  287. // intercepted by the proxy so no need for implementation,
  288. // but needed to prevent set errors
  289. set: NOOP
  290. })
  291. })
  292. // expose global properties
  293. const { globalProperties } = instance.appContext.config
  294. Object.keys(globalProperties).forEach(key => {
  295. Object.defineProperty(target, key, {
  296. configurable: true,
  297. enumerable: false,
  298. get: () => globalProperties[key],
  299. set: NOOP
  300. })
  301. })
  302. return target as ComponentRenderContext
  303. }
  304. // dev only
  305. export function exposePropsOnRenderContext(
  306. instance: ComponentInternalInstance
  307. ) {
  308. const {
  309. ctx,
  310. type: { props: propsOptions }
  311. } = instance
  312. if (propsOptions) {
  313. Object.keys(normalizePropsOptions(propsOptions)[0]!).forEach(key => {
  314. Object.defineProperty(ctx, key, {
  315. enumerable: true,
  316. configurable: true,
  317. get: () => instance.props[key],
  318. set: NOOP
  319. })
  320. })
  321. }
  322. }
  323. // dev only
  324. export function exposeSetupStateOnRenderContext(
  325. instance: ComponentInternalInstance
  326. ) {
  327. const { ctx, setupState } = instance
  328. Object.keys(toRaw(setupState)).forEach(key => {
  329. Object.defineProperty(ctx, key, {
  330. enumerable: true,
  331. configurable: true,
  332. get: () => setupState[key],
  333. set: NOOP
  334. })
  335. })
  336. }