componentPublicInstance.ts 16 KB

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