componentEmits.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import {
  2. EMPTY_OBJ,
  3. type OverloadParameters,
  4. type UnionToIntersection,
  5. camelize,
  6. extend,
  7. hasOwn,
  8. hyphenate,
  9. isArray,
  10. isFunction,
  11. isObject,
  12. isOn,
  13. isString,
  14. looseToNumber,
  15. toHandlerKey,
  16. } from '@vue/shared'
  17. import {
  18. type ComponentInternalInstance,
  19. type ComponentOptions,
  20. type ConcreteComponent,
  21. type GenericComponentInstance,
  22. formatComponentName,
  23. } from './component'
  24. import { ErrorCodes, callWithAsyncErrorHandling } from './errorHandling'
  25. import { warn } from './warning'
  26. import { devtoolsComponentEmit } from './devtools'
  27. import type { AppContext } from './apiCreateApp'
  28. import { emit as compatInstanceEmit } from './compat/instanceEventEmitter'
  29. import {
  30. compatModelEmit,
  31. compatModelEventPrefix,
  32. } from './compat/componentVModel'
  33. import type { ComponentTypeEmits } from './apiSetupHelpers'
  34. import { getModelModifiers } from './helpers/useModel'
  35. import type { ComponentPublicInstance } from './componentPublicInstance'
  36. export type ObjectEmitsOptions = Record<
  37. string,
  38. ((...args: any[]) => any) | null
  39. >
  40. export type EmitsOptions = ObjectEmitsOptions | string[]
  41. export type EmitsToProps<T extends EmitsOptions | ComponentTypeEmits> =
  42. T extends string[]
  43. ? {
  44. [K in `on${Capitalize<T[number]>}`]?: (...args: any[]) => any
  45. }
  46. : T extends ObjectEmitsOptions
  47. ? {
  48. [K in string & keyof T as `on${Capitalize<K>}`]?: (
  49. ...args: T[K] extends (...args: infer P) => any
  50. ? P
  51. : T[K] extends null
  52. ? any[]
  53. : never
  54. ) => any
  55. }
  56. : {}
  57. export type TypeEmitsToOptions<T extends ComponentTypeEmits> = {
  58. [K in keyof T & string]: T[K] extends [...args: infer Args]
  59. ? (...args: Args) => any
  60. : () => any
  61. } & (T extends (...args: any[]) => any
  62. ? ParametersToFns<OverloadParameters<T>>
  63. : {})
  64. type ParametersToFns<T extends any[]> = {
  65. [K in T[0]]: IsStringLiteral<K> extends true
  66. ? (
  67. ...args: T extends [e: infer E, ...args: infer P]
  68. ? K extends E
  69. ? P
  70. : never
  71. : never
  72. ) => any
  73. : never
  74. }
  75. type IsStringLiteral<T> = T extends string
  76. ? string extends T
  77. ? false
  78. : true
  79. : false
  80. export type ShortEmitsToObject<E> =
  81. E extends Record<string, any[]>
  82. ? {
  83. [K in keyof E]: (...args: E[K]) => any
  84. }
  85. : E
  86. export type EmitFn<
  87. Options = ObjectEmitsOptions,
  88. Event extends keyof Options = keyof Options,
  89. > =
  90. Options extends Array<infer V>
  91. ? (event: V, ...args: any[]) => void
  92. : {} extends Options // if the emit is empty object (usually the default value for emit) should be converted to function
  93. ? (event: string, ...args: any[]) => void
  94. : UnionToIntersection<
  95. {
  96. [key in Event]: Options[key] extends (...args: infer Args) => any
  97. ? (event: key, ...args: Args) => void
  98. : Options[key] extends any[]
  99. ? (event: key, ...args: Options[key]) => void
  100. : (event: key, ...args: any[]) => void
  101. }[Event]
  102. >
  103. export function emit(
  104. instance: ComponentInternalInstance,
  105. event: string,
  106. ...rawArgs: any[]
  107. ): ComponentPublicInstance | null | undefined {
  108. return baseEmit(
  109. instance,
  110. instance.vnode.props || EMPTY_OBJ,
  111. defaultPropGetter,
  112. event,
  113. ...rawArgs,
  114. )
  115. }
  116. /**
  117. * @internal for vapor only
  118. */
  119. export function baseEmit(
  120. instance: GenericComponentInstance,
  121. props: Record<string, any>,
  122. getter: (props: Record<string, any>, key: string) => unknown,
  123. event: string,
  124. ...rawArgs: any[]
  125. ): ComponentPublicInstance | null | undefined {
  126. if (instance.isUnmounted) return
  127. if (__DEV__) {
  128. const { emitsOptions, propsOptions } = instance
  129. if (emitsOptions) {
  130. if (
  131. !(event in emitsOptions) &&
  132. !(
  133. __COMPAT__ &&
  134. (event.startsWith('hook:') ||
  135. event.startsWith(compatModelEventPrefix))
  136. )
  137. ) {
  138. if (
  139. !propsOptions ||
  140. !propsOptions[0] ||
  141. !(toHandlerKey(camelize(event)) in propsOptions[0])
  142. ) {
  143. warn(
  144. `Component emitted event "${event}" but it is neither declared in ` +
  145. `the emits option nor as an "${toHandlerKey(camelize(event))}" prop.`,
  146. )
  147. }
  148. } else {
  149. const validator = emitsOptions[event]
  150. if (isFunction(validator)) {
  151. const isValid = validator(...rawArgs)
  152. if (!isValid) {
  153. warn(
  154. `Invalid event arguments: event validation failed for event "${event}".`,
  155. )
  156. }
  157. }
  158. }
  159. }
  160. }
  161. let args = rawArgs
  162. const isCompatModelListener =
  163. __COMPAT__ && compatModelEventPrefix + event in props
  164. const isModelListener = isCompatModelListener || event.startsWith('update:')
  165. // for v-model update:xxx events, apply modifiers on args
  166. // it's ok to use static get because modelModifiers can only be in the static
  167. // part of the props
  168. const modifiers = isCompatModelListener
  169. ? props.modelModifiers
  170. : isModelListener && getModelModifiers(props, event.slice(7), getter)
  171. if (modifiers) {
  172. if (modifiers.trim) {
  173. args = rawArgs.map(a => (isString(a) ? a.trim() : a))
  174. }
  175. if (modifiers.number) {
  176. args = rawArgs.map(looseToNumber)
  177. }
  178. }
  179. if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) {
  180. devtoolsComponentEmit(instance, event, args)
  181. }
  182. if (__DEV__) {
  183. const lowerCaseEvent = event.toLowerCase()
  184. if (
  185. lowerCaseEvent !== event &&
  186. getter(props, toHandlerKey(lowerCaseEvent))
  187. ) {
  188. warn(
  189. `Event "${lowerCaseEvent}" is emitted in component ` +
  190. `${formatComponentName(
  191. instance,
  192. instance.type,
  193. )} but the handler is registered for "${event}". ` +
  194. `Note that HTML attributes are case-insensitive and you cannot use ` +
  195. `v-on to listen to camelCase events when using in-DOM templates. ` +
  196. `You should probably use "${hyphenate(
  197. event,
  198. )}" instead of "${event}".`,
  199. )
  200. }
  201. }
  202. let handlerName
  203. let handler =
  204. getter(props, (handlerName = toHandlerKey(event))) ||
  205. // also try camelCase event handler (#2249)
  206. getter(props, (handlerName = toHandlerKey(camelize(event))))
  207. // for v-model update:xxx events, also trigger kebab-case equivalent
  208. // for props passed via kebab-case
  209. if (!handler && isModelListener) {
  210. handler = getter(props, (handlerName = toHandlerKey(hyphenate(event))))
  211. }
  212. if (handler) {
  213. callWithAsyncErrorHandling(
  214. handler as Function | Function[],
  215. instance,
  216. ErrorCodes.COMPONENT_EVENT_HANDLER,
  217. args,
  218. )
  219. }
  220. const onceHandler = getter(props, handlerName + `Once`)
  221. if (onceHandler) {
  222. if (!instance.emitted) {
  223. instance.emitted = {}
  224. } else if (instance.emitted[handlerName]) {
  225. return
  226. }
  227. instance.emitted[handlerName] = true
  228. callWithAsyncErrorHandling(
  229. onceHandler as Function | Function[],
  230. instance,
  231. ErrorCodes.COMPONENT_EVENT_HANDLER,
  232. args,
  233. )
  234. }
  235. if (__COMPAT__ && args) {
  236. compatModelEmit(instance as ComponentInternalInstance, event, args)
  237. return compatInstanceEmit(
  238. instance as ComponentInternalInstance,
  239. event,
  240. args,
  241. )
  242. }
  243. }
  244. export function defaultPropGetter(
  245. props: Record<string, any>,
  246. key: string,
  247. ): unknown {
  248. return props[key]
  249. }
  250. const mixinEmitsCache = new WeakMap<ConcreteComponent, ObjectEmitsOptions>()
  251. export function normalizeEmitsOptions(
  252. comp: ConcreteComponent,
  253. appContext: AppContext,
  254. asMixin = false,
  255. ): ObjectEmitsOptions | null {
  256. const cache =
  257. __FEATURE_OPTIONS_API__ && asMixin ? mixinEmitsCache : appContext.emitsCache
  258. const cached = cache.get(comp)
  259. if (cached !== undefined) {
  260. return cached
  261. }
  262. const raw = comp.emits
  263. let normalized: ObjectEmitsOptions = {}
  264. // apply mixin/extends props
  265. let hasExtends = false
  266. if (__FEATURE_OPTIONS_API__ && !isFunction(comp)) {
  267. const extendEmits = (raw: ComponentOptions) => {
  268. const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true)
  269. if (normalizedFromExtend) {
  270. hasExtends = true
  271. extend(normalized, normalizedFromExtend)
  272. }
  273. }
  274. if (!asMixin && appContext.mixins.length) {
  275. appContext.mixins.forEach(extendEmits)
  276. }
  277. if (comp.extends) {
  278. extendEmits(comp.extends)
  279. }
  280. if (comp.mixins) {
  281. comp.mixins.forEach(extendEmits)
  282. }
  283. }
  284. if (!raw && !hasExtends) {
  285. if (isObject(comp)) {
  286. cache.set(comp, null)
  287. }
  288. return null
  289. }
  290. if (isArray(raw)) {
  291. raw.forEach(key => (normalized[key] = null))
  292. } else {
  293. extend(normalized, raw)
  294. }
  295. if (isObject(comp)) {
  296. cache.set(comp, normalized)
  297. }
  298. return normalized
  299. }
  300. /**
  301. * Check if an incoming prop key is a declared emit event listener.
  302. * e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
  303. * both considered matched listeners.
  304. *
  305. * @internal for vapor only
  306. */
  307. export function isEmitListener(
  308. options: ObjectEmitsOptions | null,
  309. key: string,
  310. ): boolean {
  311. if (!options || !isOn(key)) {
  312. return false
  313. }
  314. if (__COMPAT__ && key.startsWith(compatModelEventPrefix)) {
  315. return true
  316. }
  317. key = key.slice(2).replace(/Once$/, '')
  318. return (
  319. hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
  320. hasOwn(options, hyphenate(key)) ||
  321. hasOwn(options, key)
  322. )
  323. }