componentPublicInstance.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. import {
  2. ComponentInternalInstance,
  3. Data,
  4. getExposeProxy,
  5. isStatefulComponent
  6. } from './component'
  7. import { nextTick, queueJob } from './scheduler'
  8. import { instanceWatch, WatchOptions, WatchStopHandle } from './apiWatch'
  9. import {
  10. EMPTY_OBJ,
  11. hasOwn,
  12. isGloballyWhitelisted,
  13. NOOP,
  14. extend,
  15. isString,
  16. isFunction,
  17. UnionToIntersection
  18. } from '@vue/shared'
  19. import {
  20. toRaw,
  21. shallowReadonly,
  22. track,
  23. TrackOpTypes,
  24. ShallowUnwrapRef,
  25. UnwrapNestedRefs
  26. } from '@vue/reactivity'
  27. import {
  28. ExtractComputedReturns,
  29. ComponentOptionsBase,
  30. ComputedOptions,
  31. MethodOptions,
  32. ComponentOptionsMixin,
  33. OptionTypesType,
  34. OptionTypesKeys,
  35. resolveMergedOptions,
  36. shouldCacheAccess,
  37. MergedComponentOptionsOverride,
  38. InjectToObject,
  39. ComponentInjectOptions
  40. } from './componentOptions'
  41. import { EmitsOptions, EmitFn } from './componentEmits'
  42. import { Slots } from './componentSlots'
  43. import { markAttrsAccessed } from './componentRenderUtils'
  44. import { currentRenderingInstance } from './componentRenderContext'
  45. import { warn } from './warning'
  46. import { installCompatInstanceProperties } from './compat/instance'
  47. /**
  48. * Custom properties added to component instances in any way and can be accessed through `this`
  49. *
  50. * @example
  51. * Here is an example of adding a property `$router` to every component instance:
  52. * ```ts
  53. * import { createApp } from 'vue'
  54. * import { Router, createRouter } from 'vue-router'
  55. *
  56. * declare module '@vue/runtime-core' {
  57. * interface ComponentCustomProperties {
  58. * $router: Router
  59. * }
  60. * }
  61. *
  62. * // effectively adding the router to every component instance
  63. * const app = createApp({})
  64. * const router = createRouter()
  65. * app.config.globalProperties.$router = router
  66. *
  67. * const vm = app.mount('#app')
  68. * // we can access the router from the instance
  69. * vm.$router.push('/')
  70. * ```
  71. */
  72. export interface ComponentCustomProperties {}
  73. type IsDefaultMixinComponent<T> = T extends ComponentOptionsMixin
  74. ? ComponentOptionsMixin extends T
  75. ? true
  76. : false
  77. : false
  78. type MixinToOptionTypes<T> = T extends ComponentOptionsBase<
  79. infer P,
  80. infer B,
  81. infer D,
  82. infer C,
  83. infer M,
  84. infer Mixin,
  85. infer Extends,
  86. any,
  87. any,
  88. infer Defaults
  89. >
  90. ? OptionTypesType<P & {}, B & {}, D & {}, C & {}, M & {}, Defaults & {}> &
  91. IntersectionMixin<Mixin> &
  92. IntersectionMixin<Extends>
  93. : never
  94. // ExtractMixin(map type) is used to resolve circularly references
  95. type ExtractMixin<T> = {
  96. Mixin: MixinToOptionTypes<T>
  97. }[T extends ComponentOptionsMixin ? 'Mixin' : never]
  98. type IntersectionMixin<T> = IsDefaultMixinComponent<T> extends true
  99. ? OptionTypesType<{}, {}, {}, {}, {}>
  100. : UnionToIntersection<ExtractMixin<T>>
  101. type UnwrapMixinsType<
  102. T,
  103. Type extends OptionTypesKeys
  104. > = T extends OptionTypesType ? T[Type] : never
  105. type EnsureNonVoid<T> = T extends void ? {} : T
  106. export type ComponentPublicInstanceConstructor<
  107. T extends ComponentPublicInstance<
  108. Props,
  109. RawBindings,
  110. D,
  111. C,
  112. M
  113. > = ComponentPublicInstance<any>,
  114. Props = any,
  115. RawBindings = any,
  116. D = any,
  117. C extends ComputedOptions = ComputedOptions,
  118. M extends MethodOptions = MethodOptions
  119. > = {
  120. __isFragment?: never
  121. __isTeleport?: never
  122. __isSuspense?: never
  123. new (...args: any[]): T
  124. }
  125. export type CreateComponentPublicInstance<
  126. P = {},
  127. B = {},
  128. D = {},
  129. C extends ComputedOptions = {},
  130. M extends MethodOptions = {},
  131. Mixin extends ComponentOptionsMixin = ComponentOptionsMixin,
  132. Extends extends ComponentOptionsMixin = ComponentOptionsMixin,
  133. E extends EmitsOptions = {},
  134. PublicProps = P,
  135. Defaults = {},
  136. MakeDefaultsOptional extends boolean = false,
  137. I extends ComponentInjectOptions = {},
  138. PublicMixin = IntersectionMixin<Mixin> & IntersectionMixin<Extends>,
  139. PublicP = UnwrapMixinsType<PublicMixin, 'P'> & EnsureNonVoid<P>,
  140. PublicB = UnwrapMixinsType<PublicMixin, 'B'> & EnsureNonVoid<B>,
  141. PublicD = UnwrapMixinsType<PublicMixin, 'D'> & EnsureNonVoid<D>,
  142. PublicC extends ComputedOptions = UnwrapMixinsType<PublicMixin, 'C'> &
  143. EnsureNonVoid<C>,
  144. PublicM extends MethodOptions = UnwrapMixinsType<PublicMixin, 'M'> &
  145. EnsureNonVoid<M>,
  146. PublicDefaults = UnwrapMixinsType<PublicMixin, 'Defaults'> &
  147. EnsureNonVoid<Defaults>
  148. > = ComponentPublicInstance<
  149. PublicP,
  150. PublicB,
  151. PublicD,
  152. PublicC,
  153. PublicM,
  154. E,
  155. PublicProps,
  156. PublicDefaults,
  157. MakeDefaultsOptional,
  158. ComponentOptionsBase<P, B, D, C, M, Mixin, Extends, E, string, Defaults>,
  159. I
  160. >
  161. // public properties exposed on the proxy, which is used as the render context
  162. // in templates (as `this` in the render option)
  163. export type ComponentPublicInstance<
  164. P = {}, // props type extracted from props option
  165. B = {}, // raw bindings returned from setup()
  166. D = {}, // return from data()
  167. C extends ComputedOptions = {},
  168. M extends MethodOptions = {},
  169. E extends EmitsOptions = {},
  170. PublicProps = P,
  171. Defaults = {},
  172. MakeDefaultsOptional extends boolean = false,
  173. Options = ComponentOptionsBase<any, any, any, any, any, any, any, any, any>,
  174. I extends ComponentInjectOptions = {}
  175. > = {
  176. $: ComponentInternalInstance
  177. $data: D
  178. $props: MakeDefaultsOptional extends true
  179. ? Partial<Defaults> & Omit<P & PublicProps, keyof Defaults>
  180. : P & PublicProps
  181. $attrs: Data
  182. $refs: Data
  183. $slots: Slots
  184. $root: ComponentPublicInstance | null
  185. $parent: ComponentPublicInstance | null
  186. $emit: EmitFn<E>
  187. $el: any
  188. $options: Options & MergedComponentOptionsOverride
  189. $forceUpdate: () => void
  190. $nextTick: typeof nextTick
  191. $watch<T extends string | ((...args: any) => any)>(
  192. source: T,
  193. cb: T extends (...args: any) => infer R
  194. ? (...args: [R, R]) => any
  195. : (...args: any) => any,
  196. options?: WatchOptions
  197. ): WatchStopHandle
  198. } & P &
  199. ShallowUnwrapRef<B> &
  200. UnwrapNestedRefs<D> &
  201. ExtractComputedReturns<C> &
  202. M &
  203. ComponentCustomProperties &
  204. InjectToObject<I>
  205. export type PublicPropertiesMap = Record<
  206. string,
  207. (i: ComponentInternalInstance) => any
  208. >
  209. /**
  210. * #2437 In Vue 3, functional components do not have a public instance proxy but
  211. * they exist in the internal parent chain. For code that relies on traversing
  212. * public $parent chains, skip functional ones and go to the parent instead.
  213. */
  214. const getPublicInstance = (
  215. i: ComponentInternalInstance | null
  216. ): ComponentPublicInstance | ComponentInternalInstance['exposed'] | null => {
  217. if (!i) return null
  218. if (isStatefulComponent(i)) return getExposeProxy(i) || i.proxy
  219. return getPublicInstance(i.parent)
  220. }
  221. export const publicPropertiesMap: PublicPropertiesMap =
  222. // Move PURE marker to new line to workaround compiler discarding it
  223. // due to type annotation
  224. /*#__PURE__*/ extend(Object.create(null), {
  225. $: i => i,
  226. $el: i => i.vnode.el,
  227. $data: i => i.data,
  228. $props: i => (__DEV__ ? shallowReadonly(i.props) : i.props),
  229. $attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs),
  230. $slots: i => (__DEV__ ? shallowReadonly(i.slots) : i.slots),
  231. $refs: i => (__DEV__ ? shallowReadonly(i.refs) : i.refs),
  232. $parent: i => getPublicInstance(i.parent),
  233. $root: i => getPublicInstance(i.root),
  234. $emit: i => i.emit,
  235. $options: i => (__FEATURE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type),
  236. $forceUpdate: i => i.f || (i.f = () => queueJob(i.update)),
  237. $nextTick: i => i.n || (i.n = nextTick.bind(i.proxy!)),
  238. $watch: i => (__FEATURE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP)
  239. } as PublicPropertiesMap)
  240. if (__COMPAT__) {
  241. installCompatInstanceProperties(publicPropertiesMap)
  242. }
  243. const enum AccessTypes {
  244. OTHER,
  245. SETUP,
  246. DATA,
  247. PROPS,
  248. CONTEXT
  249. }
  250. export interface ComponentRenderContext {
  251. [key: string]: any
  252. _: ComponentInternalInstance
  253. }
  254. export const isReservedPrefix = (key: string) => key === '_' || key === '$'
  255. const hasSetupBinding = (state: Data, key: string) =>
  256. state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key)
  257. export const PublicInstanceProxyHandlers: ProxyHandler<any> = {
  258. get({ _: instance }: ComponentRenderContext, key: string) {
  259. const { ctx, setupState, data, props, accessCache, type, appContext } =
  260. instance
  261. // for internal formatters to know that this is a Vue instance
  262. if (__DEV__ && key === '__isVue') {
  263. return true
  264. }
  265. // data / props / ctx
  266. // This getter gets called for every property access on the render context
  267. // during render and is a major hotspot. The most expensive part of this
  268. // is the multiple hasOwn() calls. It's much faster to do a simple property
  269. // access on a plain object, so we use an accessCache object (with null
  270. // prototype) to memoize what access type a key corresponds to.
  271. let normalizedProps
  272. if (key[0] !== '$') {
  273. const n = accessCache![key]
  274. if (n !== undefined) {
  275. switch (n) {
  276. case AccessTypes.SETUP:
  277. return setupState[key]
  278. case AccessTypes.DATA:
  279. return data[key]
  280. case AccessTypes.CONTEXT:
  281. return ctx[key]
  282. case AccessTypes.PROPS:
  283. return props![key]
  284. // default: just fallthrough
  285. }
  286. } else if (hasSetupBinding(setupState, key)) {
  287. accessCache![key] = AccessTypes.SETUP
  288. return setupState[key]
  289. } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  290. accessCache![key] = AccessTypes.DATA
  291. return data[key]
  292. } else if (
  293. // only cache other properties when instance has declared (thus stable)
  294. // props
  295. (normalizedProps = instance.propsOptions[0]) &&
  296. hasOwn(normalizedProps, key)
  297. ) {
  298. accessCache![key] = AccessTypes.PROPS
  299. return props![key]
  300. } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  301. accessCache![key] = AccessTypes.CONTEXT
  302. return ctx[key]
  303. } else if (!__FEATURE_OPTIONS_API__ || shouldCacheAccess) {
  304. accessCache![key] = AccessTypes.OTHER
  305. }
  306. }
  307. const publicGetter = publicPropertiesMap[key]
  308. let cssModule, globalProperties
  309. // public $xxx properties
  310. if (publicGetter) {
  311. if (key === '$attrs') {
  312. track(instance, TrackOpTypes.GET, key)
  313. __DEV__ && markAttrsAccessed()
  314. }
  315. return publicGetter(instance)
  316. } else if (
  317. // css module (injected by vue-loader)
  318. (cssModule = type.__cssModules) &&
  319. (cssModule = cssModule[key])
  320. ) {
  321. return cssModule
  322. } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  323. // user may set custom properties to `this` that start with `$`
  324. accessCache![key] = AccessTypes.CONTEXT
  325. return ctx[key]
  326. } else if (
  327. // global properties
  328. ((globalProperties = appContext.config.globalProperties),
  329. hasOwn(globalProperties, key))
  330. ) {
  331. if (__COMPAT__) {
  332. const desc = Object.getOwnPropertyDescriptor(globalProperties, key)!
  333. if (desc.get) {
  334. return desc.get.call(instance.proxy)
  335. } else {
  336. const val = globalProperties[key]
  337. return isFunction(val)
  338. ? Object.assign(val.bind(instance.proxy), val)
  339. : val
  340. }
  341. } else {
  342. return globalProperties[key]
  343. }
  344. } else if (
  345. __DEV__ &&
  346. currentRenderingInstance &&
  347. (!isString(key) ||
  348. // #1091 avoid internal isRef/isVNode checks on component instance leading
  349. // to infinite warning loop
  350. key.indexOf('__v') !== 0)
  351. ) {
  352. if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) {
  353. warn(
  354. `Property ${JSON.stringify(
  355. key
  356. )} must be accessed via $data because it starts with a reserved ` +
  357. `character ("$" or "_") and is not proxied on the render context.`
  358. )
  359. } else if (instance === currentRenderingInstance) {
  360. warn(
  361. `Property ${JSON.stringify(key)} was accessed during render ` +
  362. `but is not defined on instance.`
  363. )
  364. }
  365. }
  366. },
  367. set(
  368. { _: instance }: ComponentRenderContext,
  369. key: string,
  370. value: any
  371. ): boolean {
  372. const { data, setupState, ctx } = instance
  373. if (hasSetupBinding(setupState, key)) {
  374. setupState[key] = value
  375. return true
  376. } else if (
  377. __DEV__ &&
  378. setupState.__isScriptSetup &&
  379. hasOwn(setupState, key)
  380. ) {
  381. warn(`Cannot mutate <script setup> binding "${key}" from Options API.`)
  382. return false
  383. } else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  384. data[key] = value
  385. return true
  386. } else if (hasOwn(instance.props, key)) {
  387. __DEV__ && warn(`Attempting to mutate prop "${key}". Props are readonly.`)
  388. return false
  389. }
  390. if (key[0] === '$' && key.slice(1) in instance) {
  391. __DEV__ &&
  392. warn(
  393. `Attempting to mutate public property "${key}". ` +
  394. `Properties starting with $ are reserved and readonly.`
  395. )
  396. return false
  397. } else {
  398. if (__DEV__ && key in instance.appContext.config.globalProperties) {
  399. Object.defineProperty(ctx, key, {
  400. enumerable: true,
  401. configurable: true,
  402. value
  403. })
  404. } else {
  405. ctx[key] = value
  406. }
  407. }
  408. return true
  409. },
  410. has(
  411. {
  412. _: { data, setupState, accessCache, ctx, appContext, propsOptions }
  413. }: ComponentRenderContext,
  414. key: string
  415. ) {
  416. let normalizedProps
  417. return (
  418. !!accessCache![key] ||
  419. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  420. hasSetupBinding(setupState, key) ||
  421. ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
  422. hasOwn(ctx, key) ||
  423. hasOwn(publicPropertiesMap, key) ||
  424. hasOwn(appContext.config.globalProperties, key)
  425. )
  426. },
  427. defineProperty(
  428. target: ComponentRenderContext,
  429. key: string,
  430. descriptor: PropertyDescriptor
  431. ) {
  432. if (descriptor.get != null) {
  433. // invalidate key cache of a getter based property #5417
  434. target._.accessCache![key] = 0
  435. } else if (hasOwn(descriptor, 'value')) {
  436. this.set!(target, key, descriptor.value, null)
  437. }
  438. return Reflect.defineProperty(target, key, descriptor)
  439. }
  440. }
  441. if (__DEV__ && !__TEST__) {
  442. PublicInstanceProxyHandlers.ownKeys = (target: ComponentRenderContext) => {
  443. warn(
  444. `Avoid app logic that relies on enumerating keys on a component instance. ` +
  445. `The keys will be empty in production mode to avoid performance overhead.`
  446. )
  447. return Reflect.ownKeys(target)
  448. }
  449. }
  450. export const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend(
  451. {},
  452. PublicInstanceProxyHandlers,
  453. {
  454. get(target: ComponentRenderContext, key: string) {
  455. // fast path for unscopables when using `with` block
  456. if ((key as any) === Symbol.unscopables) {
  457. return
  458. }
  459. return PublicInstanceProxyHandlers.get!(target, key, target)
  460. },
  461. has(_: ComponentRenderContext, key: string) {
  462. const has = key[0] !== '_' && !isGloballyWhitelisted(key)
  463. if (__DEV__ && !has && PublicInstanceProxyHandlers.has!(_, key)) {
  464. warn(
  465. `Property ${JSON.stringify(
  466. key
  467. )} should not start with _ which is a reserved prefix for Vue internals.`
  468. )
  469. }
  470. return has
  471. }
  472. }
  473. )
  474. // dev only
  475. // In dev mode, the proxy target exposes the same properties as seen on `this`
  476. // for easier console inspection. In prod mode it will be an empty object so
  477. // these properties definitions can be skipped.
  478. export function createDevRenderContext(instance: ComponentInternalInstance) {
  479. const target: Record<string, any> = {}
  480. // expose internal instance for proxy handlers
  481. Object.defineProperty(target, `_`, {
  482. configurable: true,
  483. enumerable: false,
  484. get: () => instance
  485. })
  486. // expose public properties
  487. Object.keys(publicPropertiesMap).forEach(key => {
  488. Object.defineProperty(target, key, {
  489. configurable: true,
  490. enumerable: false,
  491. get: () => publicPropertiesMap[key](instance),
  492. // intercepted by the proxy so no need for implementation,
  493. // but needed to prevent set errors
  494. set: NOOP
  495. })
  496. })
  497. return target as ComponentRenderContext
  498. }
  499. // dev only
  500. export function exposePropsOnRenderContext(
  501. instance: ComponentInternalInstance
  502. ) {
  503. const {
  504. ctx,
  505. propsOptions: [propsOptions]
  506. } = instance
  507. if (propsOptions) {
  508. Object.keys(propsOptions).forEach(key => {
  509. Object.defineProperty(ctx, key, {
  510. enumerable: true,
  511. configurable: true,
  512. get: () => instance.props[key],
  513. set: NOOP
  514. })
  515. })
  516. }
  517. }
  518. // dev only
  519. export function exposeSetupStateOnRenderContext(
  520. instance: ComponentInternalInstance
  521. ) {
  522. const { ctx, setupState } = instance
  523. Object.keys(toRaw(setupState)).forEach(key => {
  524. if (!setupState.__isScriptSetup) {
  525. if (isReservedPrefix(key[0])) {
  526. warn(
  527. `setup() return property ${JSON.stringify(
  528. key
  529. )} should not start with "$" or "_" ` +
  530. `which are reserved prefixes for Vue internals.`
  531. )
  532. return
  533. }
  534. Object.defineProperty(ctx, key, {
  535. enumerable: true,
  536. configurable: true,
  537. get: () => setupState[key],
  538. set: NOOP
  539. })
  540. }
  541. })
  542. }