apiSetupHelpers.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import { ComponentPropsOptions } from '@vue/runtime-core'
  2. import { isArray, isPromise, isFunction } from '@vue/shared'
  3. import {
  4. getCurrentInstance,
  5. setCurrentInstance,
  6. SetupContext,
  7. createSetupContext,
  8. unsetCurrentInstance
  9. } from './component'
  10. import { EmitFn, EmitsOptions } from './componentEmits'
  11. import { ComponentObjectPropsOptions, ExtractPropTypes } from './componentProps'
  12. import { warn } from './warning'
  13. // dev only
  14. const warnRuntimeUsage = (method: string) =>
  15. warn(
  16. `${method}() is a compiler-hint helper that is only usable inside ` +
  17. `<script setup> of a single file component. Its arguments should be ` +
  18. `compiled away and passing it at runtime has no effect.`
  19. )
  20. /**
  21. * Vue `<script setup>` compiler macro for declaring component props. The
  22. * expected argument is the same as the component `props` option.
  23. *
  24. * Example runtime declaration:
  25. * ```js
  26. * // using Array syntax
  27. * const props = defineProps(['foo', 'bar'])
  28. * // using Object syntax
  29. * const props = defineProps({
  30. * foo: String,
  31. * bar: {
  32. * type: Number,
  33. * required: true
  34. * }
  35. * })
  36. * ```
  37. *
  38. * Equivalent type-based declaration:
  39. * ```ts
  40. * // will be compiled into equivalent runtime declarations
  41. * const props = defineProps<{
  42. * foo?: string
  43. * bar: number
  44. * }>()
  45. * ```
  46. *
  47. * This is only usable inside `<script setup>`, is compiled away in the
  48. * output and should **not** be actually called at runtime.
  49. */
  50. // overload 1: runtime props w/ array
  51. export function defineProps<PropNames extends string = string>(
  52. props: PropNames[]
  53. ): Readonly<{ [key in PropNames]?: any }>
  54. // overload 2: runtime props w/ object
  55. export function defineProps<
  56. PP extends ComponentObjectPropsOptions = ComponentObjectPropsOptions
  57. >(props: PP): Readonly<ExtractPropTypes<PP>>
  58. // overload 3: typed-based declaration
  59. export function defineProps<TypeProps>(): Readonly<TypeProps>
  60. // implementation
  61. export function defineProps() {
  62. if (__DEV__) {
  63. warnRuntimeUsage(`defineProps`)
  64. }
  65. return null as any
  66. }
  67. /**
  68. * Vue `<script setup>` compiler macro for declaring a component's emitted
  69. * events. The expected argument is the same as the component `emits` option.
  70. *
  71. * Example runtime declaration:
  72. * ```js
  73. * const emit = defineEmits(['change', 'update'])
  74. * ```
  75. *
  76. * Example type-based declaration:
  77. * ```ts
  78. * const emit = defineEmits<{
  79. * (event: 'change'): void
  80. * (event: 'update', id: number): void
  81. * }>()
  82. *
  83. * emit('change')
  84. * emit('update', 1)
  85. * ```
  86. *
  87. * This is only usable inside `<script setup>`, is compiled away in the
  88. * output and should **not** be actually called at runtime.
  89. */
  90. // overload 1: runtime emits w/ array
  91. export function defineEmits<EE extends string = string>(
  92. emitOptions: EE[]
  93. ): EmitFn<EE[]>
  94. export function defineEmits<E extends EmitsOptions = EmitsOptions>(
  95. emitOptions: E
  96. ): EmitFn<E>
  97. export function defineEmits<TypeEmit>(): TypeEmit
  98. // implementation
  99. export function defineEmits() {
  100. if (__DEV__) {
  101. warnRuntimeUsage(`defineEmits`)
  102. }
  103. return null as any
  104. }
  105. /**
  106. * Vue `<script setup>` compiler macro for declaring a component's exposed
  107. * instance properties when it is accessed by a parent component via template
  108. * refs.
  109. *
  110. * `<script setup>` components are closed by default - i.e. varaibles inside
  111. * the `<script setup>` scope is not exposed to parent unless explicitly exposed
  112. * via `defineExpose`.
  113. *
  114. * This is only usable inside `<script setup>`, is compiled away in the
  115. * output and should **not** be actually called at runtime.
  116. */
  117. export function defineExpose(exposed?: Record<string, any>) {
  118. if (__DEV__) {
  119. warnRuntimeUsage(`defineExpose`)
  120. }
  121. }
  122. type NotUndefined<T> = T extends undefined ? never : T
  123. type InferDefaults<T> = {
  124. [K in keyof T]?: InferDefault<T, NotUndefined<T[K]>>
  125. }
  126. type InferDefault<P, T> = T extends
  127. | number
  128. | string
  129. | boolean
  130. | symbol
  131. | Function
  132. ? T
  133. : (props: P) => T
  134. type PropsWithDefaults<Base, Defaults> = Base & {
  135. [K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
  136. }
  137. /**
  138. * Vue `<script setup>` compiler macro for providing props default values when
  139. * using type-based `defineProps` declaration.
  140. *
  141. * Example usage:
  142. * ```ts
  143. * withDefaults(defineProps<{
  144. * size?: number
  145. * labels?: string[]
  146. * }>(), {
  147. * size: 3,
  148. * labels: () => ['default label']
  149. * })
  150. * ```
  151. *
  152. * This is only usable inside `<script setup>`, is compiled away in the output
  153. * and should **not** be actually called at runtime.
  154. */
  155. export function withDefaults<Props, Defaults extends InferDefaults<Props>>(
  156. props: Props,
  157. defaults: Defaults
  158. ): PropsWithDefaults<Props, Defaults> {
  159. if (__DEV__) {
  160. warnRuntimeUsage(`withDefaults`)
  161. }
  162. return null as any
  163. }
  164. export function useSlots(): SetupContext['slots'] {
  165. return getContext().slots
  166. }
  167. export function useAttrs(): SetupContext['attrs'] {
  168. return getContext().attrs
  169. }
  170. function getContext(): SetupContext {
  171. const i = getCurrentInstance()!
  172. if (__DEV__ && !i) {
  173. warn(`useContext() called without active instance.`)
  174. }
  175. return i.setupContext || (i.setupContext = createSetupContext(i))
  176. }
  177. /**
  178. * Runtime helper for merging default declarations. Imported by compiled code
  179. * only.
  180. * @internal
  181. */
  182. export function mergeDefaults(
  183. raw: ComponentPropsOptions,
  184. defaults: Record<string, any>
  185. ): ComponentObjectPropsOptions {
  186. const props = isArray(raw)
  187. ? raw.reduce(
  188. (normalized, p) => ((normalized[p] = {}), normalized),
  189. {} as ComponentObjectPropsOptions
  190. )
  191. : raw
  192. for (const key in defaults) {
  193. const opt = props[key]
  194. if (opt) {
  195. if (isArray(opt) || isFunction(opt)) {
  196. props[key] = { type: opt, default: defaults[key] }
  197. } else {
  198. opt.default = defaults[key]
  199. }
  200. } else if (opt === null) {
  201. props[key] = { default: defaults[key] }
  202. } else if (__DEV__) {
  203. warn(`props default key "${key}" has no corresponding declaration.`)
  204. }
  205. }
  206. return props
  207. }
  208. /**
  209. * Used to create a proxy for the rest element when destructuring props with
  210. * defineProps().
  211. * @internal
  212. */
  213. export function createPropsRestProxy(
  214. props: any,
  215. excludedKeys: string[]
  216. ): Record<string, any> {
  217. const ret: Record<string, any> = {}
  218. for (const key in props) {
  219. if (!excludedKeys.includes(key)) {
  220. Object.defineProperty(ret, key, {
  221. enumerable: true,
  222. get: () => props[key]
  223. })
  224. }
  225. }
  226. return ret
  227. }
  228. /**
  229. * `<script setup>` helper for persisting the current instance context over
  230. * async/await flows.
  231. *
  232. * `@vue/compiler-sfc` converts the following:
  233. *
  234. * ```ts
  235. * const x = await foo()
  236. * ```
  237. *
  238. * into:
  239. *
  240. * ```ts
  241. * let __temp, __restore
  242. * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
  243. * ```
  244. * @internal
  245. */
  246. export function withAsyncContext(getAwaitable: () => any) {
  247. const ctx = getCurrentInstance()!
  248. if (__DEV__ && !ctx) {
  249. warn(
  250. `withAsyncContext called without active current instance. ` +
  251. `This is likely a bug.`
  252. )
  253. }
  254. let awaitable = getAwaitable()
  255. unsetCurrentInstance()
  256. if (isPromise(awaitable)) {
  257. awaitable = awaitable.catch(e => {
  258. setCurrentInstance(ctx)
  259. throw e
  260. })
  261. }
  262. return [awaitable, () => setCurrentInstance(ctx)]
  263. }