componentEmits.ts 8.1 KB

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