new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vue · API reference · all subjects

application api

86 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

app.version example in plugin

Example showing version check inside a plugin: ```js export default { install(app) { const version = Number(app.version.split('.')[0]) if (version < 3) { console.warn('This plugin requires Vue 3') } } } ```

createApp() signature

The createApp() function creates an application instance. It takes two parameters: rootComponent (required, type Component) and rootProps (optional, type object). It returns an App instance.

createSSRApp() for server-side rendering

The createSSRApp() function creates an application instance in SSR Hydration mode. Its usage is exactly the same as createApp().

app.mount() signature and behavior

The mount() method on App interface has signature: mount(rootContainer: Element | string): ComponentPublicInstance. The rootContainer argument can be an actual DOM element or a CSS selector string. It returns the root component instance. If the component has a template or render function, it replaces existing DOM nodes in the container. Otherwise, if the runtime compiler is available, it uses the container's innerHTML as the template. In SSR hydration mode, it hydrates existing DOM nodes and morphs them if there are mismatches. mount() can only be called once per app instance.

app.unmount() signature

The unmount() method on App interface has signature: unmount(): void. It unmounts a mounted application instance and triggers unmount lifecycle hooks for all components in the component tree.

app.onUnmount() for cleanup callbacks

The onUnmount() method on App interface has signature: onUnmount(callback: () => any): void. It registers a callback to be called when the app is unmounted. Available in Vue 3.5+.

app.component() for global component registration

The component() method on App interface has two overloads: component(name: string): Component | undefined (retrieves a registered component) and component(name: string, component: Component): this (registers a component and returns the app instance). Passing both name and component registers a global component. Passing only name retrieves an already registered component.

app.directive() for global directive registration

The directive() method on App interface has two overloads: directive(name: string): Directive | undefined (retrieves a registered directive) and directive(name: string, directive: Directive): this (registers a directive and returns the app instance). A directive can be either an object directive with custom directive hooks or a function directive shorthand.

app.use() for plugin installation

The use() method on App interface has signature: use(plugin: Plugin, ...options: any[]): this. It installs a plugin. The first argument is the plugin (either an object with an install() method or a function that serves as install()). Optional plugin options are passed as additional arguments and forwarded to the plugin's install() method. If app.use() is called on the same plugin multiple times, the plugin is installed only once.

app.mixin() for global mixins

The mixin() method on App interface has signature: mixin(mixin: ComponentOptions): this. It applies a global mixin scoped to the application. A global mixin applies its included options to every component instance in the application. Mixins are supported mainly for backwards compatibility; composables are preferred for logic reuse.

app.provide() signature and usage

The provide() method on App interface has signature: provide<T>(key: InjectionKey<T> | symbol | string, value: T): this. It provides a value that can be injected in all descendant components within the application. The injection key is the first argument and the provided value is the second. It returns the application instance.

app.runWithContext() for injection context

The runWithContext() method on App interface has signature: runWithContext<T>(fn: () => T): T. Available in Vue 3.3+. It executes a callback with the current app as the injection context. During the synchronous call, inject() calls can look up injections from app-provided values even without an active component instance. The callback's return value is returned.

app.version property

The version property on App interface has type: string. It provides the version of Vue that the application was created with. This is useful inside plugins for conditional logic based on different Vue versions.

createApp() example with inline root component

Example showing createApp with an inline root component: ```js import { createApp } from 'vue' const app = createApp({ /* root component options */ }) ```

createApp() example with imported component

Example showing createApp with an imported Vue component: ```js import { createApp } from 'vue' import App from './App.vue' const app = createApp(App) ```

app.mount() example with CSS selector

Example showing app.mount() with a CSS selector: ```js import { createApp } from 'vue' const app = createApp(/* ... */) app.mount('#app') ```

app.mount() example with DOM element

Example showing app.mount() with an actual DOM element: ```js app.mount(document.body.firstChild) ```

app.component() registration and retrieval example

Example showing global component registration and retrieval: ```js import { createApp } from 'vue' const app = createApp({}) // register an options object app.component('MyComponent', { /* ... */ }) // retrieve a registered component const MyComponent = app.component('MyComponent') ```

app.directive() registration and retrieval example

Example showing global directive registration and retrieval: ```js import { createApp } from 'vue' const app = createApp({ /* ... */ }) // register (object directive) app.directive('myDirective', { /* custom directive hooks */ }) // register (function directive shorthand) app.directive('myDirective', () => { /* ... */ }) // retrieve a registered directive const myDirective = app.directive('myDirective') ```

app.use() plugin installation example

Example showing plugin installation: ```js import { createApp } from 'vue' import MyPlugin from './plugins/MyPlugin' const app = createApp({ /* ... */ }) app.use(MyPlugin) ```

app.provide() and inject example

Example showing provide() and inject() together: ```js import { createApp } from 'vue' const app = createApp(/* ... */) app.provide('message', 'hello') ``` Inside a component using Composition API: ```js import { inject } from 'vue' export default { setup() { console.log(inject('message')) // 'hello' } } ``` Or using Options API: ```js export default { inject: ['message'], created() { console.log(this.message) // 'hello' } } ```

app.runWithContext() example

Example showing runWithContext() usage: ```js import { inject } from 'vue' app.provide('id', 1) const injected = app.runWithContext(() => { return inject('id') }) console.log(injected) // 1 ```

inject() synchronous requirement and TypeScript support

Similar to lifecycle hook registration APIs, inject() must be called synchronously during a component's setup() phase. When using TypeScript, the key can be of type InjectionKey, a Vue-provided utility type extending Symbol, which syncs the value type between provide() and inject().

hasInjectionContext() function

The hasInjectionContext() function is only supported in Vue 3.3+. It has the signature: function hasInjectionContext(): boolean and returns true if inject() can be used without warning about being called in the wrong place (e.g. outside of setup()). This method is designed for use by libraries that want to use inject() internally without triggering a warning to end users.

provide() function signature and behavior

The provide() function has the signature: function provide<T>(key: InjectionKey<T> | string, value: T): void. It takes two arguments: a key (string or symbol) and a value to be injected by descendant components. When using TypeScript, the key can be a symbol casted as InjectionKey, which is a Vue-provided utility type extending Symbol, used to sync value types between provide() and inject(). The provide() function must be called synchronously during a component's setup() phase.

provide() example with static value, reactive value, and symbol keys

Example demonstrating provide(): provide('path', '/project/') provides a static string value; const count = ref(0); provide('count', count) provides a reactive ref; provide(countSymbol, count) provides a value with a Symbol key. These examples show provide() called in a <script setup> block.

inject() function signatures with and without default values

The inject() function has three signatures: (1) function inject<T>(key: InjectionKey<T> | string): T | undefined for injection without default value, returns undefined if not found; (2) function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T with a default value; (3) function inject<T>(key: InjectionKey<T> | string, defaultValue: () => T, treatDefaultAsFactory: true): T with a factory function as default value, requiring true as the third argument.

inject() resolution and shadowing behavior

Vue walks up the parent chain to locate a provided value with a matching injection key. If multiple components in the parent chain provide the same key, the one closest to the injecting component will shadow those higher up the chain and its value will be used. If no matching value is found, inject() returns undefined unless a default value is provided.

inject() with factory function default

The second argument to inject() can be a factory function that returns values expensive to create. When using a factory function as the default value, true must be passed as the third argument (treatDefaultAsFactory: true) to indicate the function should be used as a factory instead of being used as the value itself.

inject() example with various usage patterns

Example demonstrating inject(): const path = inject('path') injects static value without default; const count = inject('count') injects reactive value; const count2 = inject(countSymbol) injects with Symbol keys; const bar = inject('path', '/default-path') injects with default value; const fn = inject('function', () => {}) injects with function default; const baz = inject('factory', () => new ExpensiveObject(), true) injects with factory default value.

defineCustomElement() signature and return type

defineCustomElement() accepts the same argument as defineComponent, but returns a native Custom Element class constructor. The function signature is: function defineCustomElement(component: (ComponentOptions & CustomElementsOptions) | ComponentOptions['setup'], options?: CustomElementsOptions): { new (props?: object): HTMLElement }. The return value is a custom element constructor that can be registered using customElements.define().

defineCustomElement() options can be passed as second argument

Instead of being passed as part of the component itself, CustomElementsOptions can also be passed via a second argument to defineCustomElement(). For example: defineCustomElement(Element, { configureApp(app) { /* ... */ } }).

defineCustomElement() example usage

Example of using defineCustomElement(): import { defineCustomElement } from 'vue'; const MyVueElement = defineCustomElement({ /* component options */ }); customElements.define('my-vue-element', MyVueElement);

CustomElementsOptions interface

The CustomElementsOptions interface has the following properties: styles (string[], optional) - an array of inlined CSS strings for providing CSS that should be injected into the element's shadow root; configureApp (function, optional, 3.5+) - a function that can be used to configure the Vue app instance for the custom element; shadowRoot (boolean, optional, 3.5+, defaults to true) - set to false to render the custom element without a shadow root, which means <style> in custom element SFCs will no longer be encapsulated; nonce (string, optional, 3.5+) - if provided, will be set as the nonce attribute on style tags injected to the shadow root.

RendererOptions createElement method signature

The createElement method in RendererOptions takes parameters: type (string), and optional namespace (ElementNamespace), isCustomizedBuiltIn (string), and vnodeProps (VNodeProps & { [key: string]: any } | null). It returns a HostElement.

RendererOptions querySelector method signature

The querySelector method in RendererOptions is optional and takes a single parameter selector (string). It returns HostElement | null and is used to query elements by selector.

RendererOptions setElementText method signature

The setElementText method in RendererOptions takes parameters: node (HostElement) and text (string). It returns void and updates the text content of an element.

RendererOptions parentNode method signature

The parentNode method in RendererOptions takes a single parameter node (HostNode) and returns HostElement | null. It retrieves the parent node of a given node.

createRenderer function signature and return type

createRenderer is a function that accepts a RendererOptions object with generic types HostNode and HostElement. It returns a Renderer object with two properties: render (a RootRenderFunction) and createApp (a CreateAppFunction).

RendererOptions patchProp method signature

The patchProp method in RendererOptions takes parameters: el (HostElement), key (string), prevValue (any), nextValue (any), and optional namespace (ElementNamespace) and parentComponent (ComponentInternalInstance | null). It returns void and is used to update element properties.

RendererOptions insert method signature

The insert method in RendererOptions takes parameters: el (HostNode), parent (HostElement), and optional anchor (HostNode | null). It returns void and is used to insert a node into the DOM.

RendererOptions remove method signature

The remove method in RendererOptions takes a single parameter el (HostNode) and returns void. It is used to remove a node from the DOM.

RendererOptions nextSibling method signature

The nextSibling method in RendererOptions takes a single parameter node (HostNode) and returns HostNode | null. It retrieves the next sibling node.

RendererOptions createText method signature

The createText method in RendererOptions takes a single parameter text (string) and returns a HostNode. It is used to create a text node.

RendererOptions createComment method signature

The createComment method in RendererOptions takes a single parameter text (string) and returns a HostNode. It is used to create a comment node.

RendererOptions setScopeId method signature

The setScopeId method in RendererOptions is optional and takes parameters: el (HostElement) and id (string). It returns void and is used to set a scoped ID on an element.

RendererOptions cloneNode method signature

The cloneNode method in RendererOptions is optional and takes a single parameter node (HostNode). It returns HostNode and is used to clone a node.

RendererOptions insertStaticContent method signature

The insertStaticContent method in RendererOptions is optional and takes parameters: content (string), parent (HostElement), anchor (HostNode | null), namespace (ElementNamespace), and optional start (HostNode | null) and end (HostNode | null). It returns a tuple [HostNode, HostNode] representing the start and end nodes of inserted content.

createRenderer enables custom rendering for non-DOM environments

createRenderer creates a custom renderer by accepting platform-specific node creation and manipulation APIs. This allows Vue's core runtime to target non-DOM environments by providing custom implementations of DOM-related operations.

createRenderer example with re-exports

A custom renderer can be created by destructuring render and createApp from createRenderer, passing it options like patchProp, insert, remove, and createElement. The module should export both the render and createApp functions along with re-exported core APIs from @vue/runtime-core.

version global API

The version property exposes the current version of Vue as a string. Import it with: import { version } from 'vue'

nextTick signature and usage

nextTick() has the signature: function nextTick(callback?: () => void): Promise<void>. It is a utility for waiting for the next DOM update flush. When reactive state is mutated in Vue, the resulting DOM updates are not applied synchronously. Instead, Vue buffers them until the next tick to ensure that each component updates only once no matter how many state changes have been made. nextTick() can be used immediately after a state change to wait for the DOM updates to complete. You can either pass a callback as an argument, or await the returned Promise.

nextTick example with composition API

Example showing nextTick with composition API: ```vue <script setup> import { ref, nextTick } from 'vue' const count = ref(0) async function increment() { count.value++ // DOM not yet updated console.log(document.getElementById('counter').textContent) // 0 await nextTick() // DOM is now updated console.log(document.getElementById('counter').textContent) // 1 } </script> <template> <button id="counter" @click="increment">{{ count }}</button> </template> ``` This demonstrates that DOM updates occur after awaiting nextTick().

nextTick example with options API

Example showing nextTick with options API: ```vue <script> import { nextTick } from 'vue' export default { data() { return { count: 0 } }, methods: { async increment() { this.count++ // DOM not yet updated console.log(document.getElementById('counter').textContent) // 0 await nextTick() // DOM is now updated console.log(document.getElementById('counter').textContent) // 1 } } } </script> <template> <button id="counter" @click="increment">{{ count }}</button> </template> ``` This demonstrates that DOM updates occur after awaiting nextTick().

defineComponent signature and purpose

defineComponent() is a type helper for defining a Vue component with type inference. The options syntax has the signature: function defineComponent(component: ComponentOptions): ComponentConstructor. The function is essentially a runtime no-op for type inference purposes only. The return type is a constructor type whose instance type is the inferred component instance type based on the options. This is used for type inference when the returned type is used as a tag in TSX. The instance type of a component can be extracted from the return type using: const Foo = defineComponent(/* ... */); type FooInstance = InstanceType<typeof Foo>

defineComponent function signature (3.3+)

defineComponent() also has an alternative function signature supported in 3.3+ that is meant to be used with the Composition API and render functions or JSX. Instead of passing in an options object, a function is expected instead. This function works the same as the Composition API setup() function: it receives the props and the setup context. The return value should be a render function - both h() and JSX are supported. The signature is: function defineComponent(setup: ComponentOptions['setup'], extraOptions?: ComponentOptions): () => any

defineComponent function signature with render function example

Example of defineComponent with function signature using render functions: ```js import { ref, h } from 'vue' const Comp = defineComponent( (props) => { // use Composition API here like in <script setup> const count = ref(0) return () => { // render function or JSX return h('div', count.value) } }, // extra options, e.g. declare props and emits { props: { /* ... */ } } ) ``` This signature supports generics and is particularly useful with TypeScript and TSX.

defineComponent TSX generics example

Example of defineComponent with TypeScript generics: ```tsx const Comp = defineComponent( <T extends string | number>(props: { msg: T; list: T[] }) => { // use Composition API here like in <script setup> const count = ref(0) return () => { // render function or JSX return <div>{count.value}</div> } }, // manual runtime props declaration is currently still needed. { props: ['msg', 'list'] } ) ``` Manual runtime props declaration is currently still required, though a future Babel plugin is planned to automatically infer and inject the runtime props.

defineComponent webpack tree-shaking note

Because defineComponent() is a function call, some build tools like webpack may think it produces side-effects, which prevents tree-shaking of unused components. To indicate the function call is safe to tree-shake, add a /*#__PURE__*/ comment before the call: export default /*#__PURE__*/ defineComponent(/* ... */). This is not necessary when using Vite, because Rollup (the underlying production bundler) is smart enough to determine that defineComponent() is side-effect-free without manual annotations.

defineAsyncComponent signature and purpose

defineAsyncComponent() defines an async component which is lazy loaded only when it is rendered. The signature is: function defineAsyncComponent(source: AsyncComponentLoader | AsyncComponentOptions): Component where AsyncComponentLoader = () => Promise<Component>

Give your agent this brain