### Basic
```
--------------------------------
### Using the Setup Context
Source: https://vuejs.org/api/composition-api-setup
Accessing attrs, slots, emit, and expose via the second argument of setup().
```javascript
export default {
setup(props, context) {
// Attributes (Non-reactive object, equivalent to $attrs)
console.log(context.attrs)
// Slots (Non-reactive object, equivalent to $slots)
console.log(context.slots)
// Emit events (Function, equivalent to $emit)
console.log(context.emit)
// Expose public properties (Function)
console.log(context.expose)
}
}
```
```javascript
export default {
setup(props, { attrs, slots, emit, expose }) {
...
}
}
```
--------------------------------
### Install Vue Plugin
Source: https://vuejs.org/api/application
Install a Vue plugin using `app.use()`. The plugin can be an object with an `install` method or a function. Optional options can be passed as the second argument.
```js
import { createApp } from 'vue'
import MyPlugin from './plugins/MyPlugin'
const app = createApp({
/* ... */
})
app.use(MyPlugin)
```
--------------------------------
### Vue Composition API Extends Example
Source: https://vuejs.org/api/options-composition
Illustrates extending a base component in Vue's Composition API by calling the base component's `setup()` within the extending component's `setup()`.
```js
import Base from './Base.js'
export default {
extends: Base,
setup(props, ctx) {
return {
...Base.setup(props, ctx),
// local bindings
}
}
}
```
--------------------------------
### $watch() Usage Examples
Source: https://vuejs.org/api/component-instance
Examples demonstrating how to watch properties, paths, expressions, and how to stop a watcher.
```js
this.$watch('a', (newVal, oldVal) => {})
```
```js
this.$watch('a.b', (newVal, oldVal) => {})
```
```js
this.$watch(
// every time the expression `this.a + this.b` yields
// a different result, the handler will be called.
// It's as if we were watching a computed property
// without defining the computed property itself.
() => this.a + this.b,
(newVal, oldVal) => {}
)
```
```js
const unwatch = this.$watch('a', cb)
// later...
unwatch()
```
--------------------------------
### Configuration Guides
Source: https://vuejs.org/api/compile-time-flags
Guides on how to configure Vue.js compile-time flags using different build tools.
```APIDOC
## Configuration Guides
### Vite
`@vitejs/plugin-vue` automatically provides default values for these flags. To change the default values, use Vite's [`define` config option](https://vite.dev/config/shared-options.html#define):
```js [vite.config.js]
import { defineConfig } from 'vite'
export default defineConfig({
define: {
// enable hydration mismatch details in production build
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'true'
}
})
```
### vue-cli
`@vue/cli-service` automatically provides default values for some of these flags. To configure /change the values:
```js [vue.config.js]
module.exports = {
chainWebpack: (config) => {
config.plugin('define').tap((definitions) => {
Object.assign(definitions[0], {
__VUE_OPTIONS_API__: 'true',
__VUE_PROD_DEVTOOLS__: 'false',
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
})
return definitions
})
}
}
```
### webpack
Flags should be defined using webpack's [DefinePlugin](https://webpack.js.org/plugins/define-plugin/):
```js [webpack.config.js]
module.exports = {
// ...
plugins: [
new webpack.DefinePlugin({
__VUE_OPTIONS_API__: 'true',
__VUE_PROD_DEVTOOLS__: 'false',
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
})
]
}
```
### Rollup
Flags should be defined using [@rollup/plugin-replace](https://github.com/rollup/plugins/tree/master/packages/replace):
```js [rollup.config.js]
import replace from '@rollup/plugin-replace'
export default {
plugins: [
replace({
__VUE_OPTIONS_API__: 'true',
__VUE_PROD_DEVTOOLS__: 'false',
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
})
]
}
```
```
--------------------------------
### Accessing props in setup()
Source: https://vuejs.org/api/composition-api-setup
Shows how to access reactive props within the setup function.
```javascript
export default {
props: {
title: String
},
setup(props) {
console.log(props.title)
}
}
```
--------------------------------
### Plugin Installation
Source: https://vuejs.org/api/application
Method for installing plugins into the Vue application.
```APIDOC
## app.use()
### Description
Installs a [plugin](/guide/reusability/plugins).
### Details
Expects the plugin as the first argument, and optional plugin options as the second argument.
The plugin can either be an object with an `install()` method, or just a function that will be used as the `install()` method. The options (second argument of `app.use()`) will be passed along to the plugin's `install()` method.
When `app.use()` is called on the same plugin multiple times, the plugin will be installed only once.
### Example
```js
import { createApp } from 'vue'
import MyPlugin from './plugins/MyPlugin'
const app = createApp({
/* ... */
})
app.use(MyPlugin)
```
### See also
[Plugins](/guide/reusability/plugins)
```
--------------------------------
### Vue.js Setup with Render Function
Source: https://vuejs.org/api/composition-api-setup
Use this pattern when you need to return a render function from `setup` to directly access reactive state. Ensure all necessary imports are included.
```js
import { h, ref } from 'vue'
export default {
setup() {
const count = ref(0)
return () => h('div', count.value)
}
}
```
--------------------------------
### Combine
```
--------------------------------
### useAttrs()
Source: https://vuejs.org/api/composition-api-helpers
Returns the attrs object from the Setup Context, including fallthrough attributes. Useful in `
```
--------------------------------
### Basic Provide Example
Source: https://vuejs.org/api/options-composition
Demonstrates basic usage of the `provide` option with static values and a Symbol key.
```javascript
const s = Symbol()
export default {
provide: {
foo: 'foo',
[s]: 'bar'
}
}
```
--------------------------------
### Vue.js Setup with Render Function and Exposed Methods
Source: https://vuejs.org/api/composition-api-setup
When a render function is returned from `setup`, use `expose()` to make component methods like `increment` accessible to parent components via template refs. This pattern requires importing `h` and `ref` from 'vue'.
```js
import { h, ref } from 'vue'
export default {
setup(props, { expose }) {
const count = ref(0)
const increment = () => ++count.value
expose({
increment
})
return () => h('div', count.value)
}
}
```
--------------------------------
### useSlots()
Source: https://vuejs.org/api/composition-api-helpers
Returns the slots object from the Setup Context, providing access to parent-passed slots as callable functions. Preferred over `defineSlots()` in `
```
--------------------------------
### Import modules in
```
--------------------------------
### Create components with h()
Source: https://vuejs.org/api/render-function
Examples of creating component vnodes, including passing props and slots.
```js
import Foo from './Foo.vue'
// passing props
h(Foo, {
// equivalent of some-prop="hello"
someProp: 'hello',
// equivalent of @update="() => {}"
onUpdate: () => {}
})
// passing single default slot
h(Foo, () => 'default slot')
// passing named slots
// notice the `null` is required to avoid
// slots object being treated as props
h(MyComponent, null, {
default: () => 'default slot',
foo: () => h('div', 'foo'),
bar: () => [h('span', 'one'), h('span', 'two')]
})
```
--------------------------------
### Methods Implementation
Source: https://vuejs.org/api/options-state
Example of declaring and invoking a method within a component.
```js
export default {
data() {
return { a: 1 }
},
methods: {
plus() {
this.a++
}
},
created() {
this.plus()
console.log(this.a) // => 2
}
}
```
--------------------------------
### useSlots() & useAttrs()
Source: https://vuejs.org/api/sfc-script-setup
Runtime helpers to access slots and attributes within
```
--------------------------------
### Composition API Component with Render Function
Source: https://vuejs.org/api/general
Example of defining a Vue component using `defineComponent` with the Composition API and a render function. Supports Composition API logic within the setup function.
```javascript
import { ref, h } from 'vue'
const Comp = defineComponent(
(props) => {
// use Composition API here like in
```
--------------------------------
### useModel Helper and Usage
Source: https://vuejs.org/api/composition-api-helpers
Type definitions and usage example for the useModel helper.
```ts
function useModel(
props: Record,
key: string,
options?: DefineModelOptions
): ModelRef
type DefineModelOptions = {
get?: (v: T) => any
set?: (v: T) => any
}
type ModelRef = Ref & [
ModelRef,
Record
]
```
```js
export default {
props: ['count'],
emits: ['update:count'],
setup(props) {
const msg = useModel(props, 'count')
msg.value = 1
}
}
```
--------------------------------
### provide()
Source: https://vuejs.org/api/composition-api-dependency-injection
Provides a value that can be injected by descendant components. Must be called synchronously during setup().
```APIDOC
## provide()
### Description
Provides a value that can be injected by descendant components. Must be called synchronously during the component's setup() phase.
### Parameters
- **key** (InjectionKey | string) - Required - The key used to identify the provided value.
- **value** (T) - Required - The value to be provided.
```
--------------------------------
### Basic Inject Example
Source: https://vuejs.org/api/options-composition
Demonstrates basic usage of the `inject` option to access a provided value named 'foo'.
```javascript
export default {
inject: ['foo'],
created() {
console.log(this.foo)
}
}
```
--------------------------------
### Implement serverPrefetch for data fetching
Source: https://vuejs.org/api/options-lifecycle
Example of using serverPrefetch to fetch data on the server and falling back to client-side fetching if necessary.
```js
export default {
data() {
return {
data: null
}
},
async serverPrefetch() {
// component is rendered as part of the initial request
// pre-fetch data on server as it is faster than on the client
this.data = await fetchOnServer(/* ... */)
},
async mounted() {
if (!this.data) {
// if data is null on mount, it means the component
// is dynamically rendered on the client. Perform a
// client-side fetch instead.
this.data = await fetchOnClient(/* ... */)
}
}
}
```
--------------------------------
### TransitionGroup Component Usage Example
Source: https://vuejs.org/api/built-in-components
Example of using TransitionGroup to animate a list of items.
```vue-html
{{ item.text }}
```
--------------------------------
### watch() API
Source: https://vuejs.org/api/reactivity-core
Detailed documentation for the watch() function, including parameters, options, and usage examples.
```APIDOC
## watch(source, callback, options)
### Description
Watches one or more reactive data sources and invokes a callback function when the sources change. It is lazy by default.
### Parameters
- **source** (WatchSource | WatchSource[]) - Required - The reactive data source to watch (ref, getter, or reactive object).
- **callback** (WatchCallback) - Required - The function to execute when the source changes. Receives (newValue, oldValue, onCleanup).
- **options** (WatchOptions) - Optional - Configuration object.
#### WatchOptions
- **immediate** (boolean) - Optional - Trigger the callback immediately on watcher creation.
- **deep** (boolean | number) - Optional - Force deep traversal of the source.
- **flush** ('pre' | 'post' | 'sync') - Optional - Adjust callback flush timing.
- **once** (boolean) - Optional - Run the callback only once (3.4+).
- **onTrack / onTrigger** (Function) - Optional - Debugging hooks.
### Request Example
```js
// Watching a ref
watch(count, (newValue, oldValue) => {
console.log('Count changed:', newValue);
});
// Watching multiple sources
watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
/* ... */
});
```
### Response
- **WatchHandle** (Object) - Returns an object containing `stop()`, `pause()`, and `resume()` methods to control the watcher lifecycle.
```
--------------------------------
### Clone a vnode with cloneVNode()
Source: https://vuejs.org/api/render-function
Example of cloning an existing vnode and merging extra props.
```js
import { h, cloneVNode } from 'vue'
const original = h('div')
const cloned = cloneVNode(original, { id: 'foo' })
```
--------------------------------
### Demonstrate defineModel de-synchronization
Source: https://vuejs.org/api/sfc-script-setup
Example showing potential de-synchronization when using default values with defineModel.
```vue
```
```vue
```
--------------------------------
### Get Vue Version
Source: https://vuejs.org/api/general
Import and log the current version of Vue.js.
```js
import { version } from 'vue'
console.log(version)
```
--------------------------------
### $emit() Usage Example
Source: https://vuejs.org/api/component-instance
Triggering custom events with or without additional arguments.
```js
export default {
created() {
// only event
this.$emit('foo')
// with additional arguments
this.$emit('bar', 1, 2, 3)
}
}
```
--------------------------------
### Vue Extends Example
Source: https://vuejs.org/api/options-composition
Shows how to use the `extends` option to inherit component options, similar to mixins but expressing inheritance intent.
```js
const CompA = { ... }
const CompB = {
extends: CompA,
...
}
```
--------------------------------
### created
Source: https://vuejs.org/api/options-lifecycle
Called after the instance has finished processing all state-related options. Reactive data, computed properties, methods, and watchers are set up, but the mounting phase has not started.
```APIDOC
## created
### Description
Called after the instance has finished processing all state-related options.
### Method
Options API Hook
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
### Details
When this hook is called, the following have been set up: reactive data, computed properties, methods, and watchers. However, the mounting phase has not been started, and the `$el` property will not be available yet.
```
--------------------------------
### Create native elements with h()
Source: https://vuejs.org/api/render-function
Examples of creating native HTML elements using the h() function.
```js
import { h } from 'vue'
// all arguments except the type are optional
h('div')
h('div', { id: 'foo' })
// both attributes and properties can be used in props
// Vue automatically picks the right way to assign it
h('div', { class: 'bar', innerHTML: 'hello' })
// class and style have the same object / array
// value support like in templates
h('div', { class: [foo, { bar }], style: { color: 'red' } })
// event listeners should be passed as onXxx
h('div', { onClick: () => {} })
// children can be a string
h('div', { id: 'foo' }, 'hello')
// props can be omitted when there are no props
h('div', 'hello')
h('div', [h('span', 'hello')])
// children array can contain mixed vnodes and strings
h('div', ['hello', h('span', 'hello')])
```
--------------------------------
### Render dynamic components with
Source: https://vuejs.org/api/built-in-special-elements
Examples of rendering components dynamically using registered names or direct definitions.
```vue
```
```vue
```
--------------------------------
### useTemplateRef Type and Usage
Source: https://vuejs.org/api/composition-api-helpers
Type definition and component usage example for accessing template refs.
```ts
function useTemplateRef(key: string): Readonly>
```
```vue
```
--------------------------------
### Creating a Custom Renderer Instance
Source: https://vuejs.org/api/custom-renderer
Example of creating a custom renderer instance by providing the necessary DOM manipulation functions. The `render` function is for low-level updates, while `createApp` returns a Vue app instance.
```javascript
import { createRenderer } from '@vue/runtime-core'
const { render, createApp } = createRenderer({
patchProp,
insert,
remove,
createElement
// ...
})
// `render` is the low-level API
// `createApp` returns an app instance
export { render, createApp }
// re-export Vue core APIs
export * from '@vue/runtime-core'
```
--------------------------------
### Transition Component Usage Examples
Source: https://vuejs.org/api/built-in-components
Various ways to implement the Transition component for elements, keys, dynamic components, and events.
```vue-html
toggled content
```
```vue-html
{{ text }}
```
```vue-html
```
```vue-html
toggled content
```
--------------------------------
### Access CSS Modules with Composition API
Source: https://vuejs.org/api/sfc-css-features
Use the useCssModule API to access CSS module classes within setup functions.
```js
import { useCssModule } from 'vue'
// inside setup() scope...
// default, returns classes for
```
--------------------------------
### beforeCreate
Source: https://vuejs.org/api/options-lifecycle
Called when the instance is initialized. Props are resolved, and state such as data() or computed will be set up. Note that Composition API's setup() hook is called before this.
```APIDOC
## beforeCreate
### Description
Called when the instance is initialized.
### Method
Options API Hook
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
### Details
Called immediately when the instance is initialized and props are resolved. Then the props will be defined as reactive properties and the state such as `data()` or `computed` will be set up. Note that the `setup()` hook of Composition API is called before any Options API hooks, even `beforeCreate()`.
```
--------------------------------
### Declare Props and Emits with Runtime Options
Source: https://vuejs.org/api/sfc-script-setup
Use defineProps and defineEmits with runtime options inside
```
--------------------------------
### useId Type and Usage
Source: https://vuejs.org/api/composition-api-helpers
Type definition and usage example for generating unique application IDs.
```ts
function useId(): string
```
```vue
```
--------------------------------
### Declare component options with defineOptions
Source: https://vuejs.org/api/sfc-script-setup
Use this macro to declare component options directly within
```
--------------------------------
### Configure KeepAlive Include and Exclude
Source: https://vuejs.org/api/built-in-components
Examples of using include and exclude props with strings, regex, and arrays.
```vue-html
```
--------------------------------
### useModel()
Source: https://vuejs.org/api/composition-api-helpers
The underlying helper for `defineModel()`, suitable for non-SFC components or when using the raw `setup()` function. Requires manual declaration of props and emits.
```APIDOC
## useModel() {#usemodel}
### Description
This is the underlying helper that powers [`defineModel()`](/api/sfc-script-setup#definemodel). If using `
```
### Response
#### Success Response (Implicit)
When a parent component accesses the instance of this component via template refs, the retrieved instance will have the shape defined in the `defineExpose` object.
#### Response Example
```json
{
"a": 1,
"b": 2
}
```
```
--------------------------------
### Usage of computed()
Source: https://vuejs.org/api/reactivity-core
Examples of creating read-only and writable computed properties, as well as debugging options.
```js
const count = ref(1)
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // 2
plusOne.value++ // error
```
```js
const count = ref(1)
const plusOne = computed({
get: () => count.value + 1,
set: (val) => {
count.value = val - 1
}
})
plusOne.value = 1
console.log(count.value) // 0
```
```js
const plusOne = computed(() => count.value + 1, {
onTrack(e) {
debugger
},
onTrigger(e) {
debugger
}
})
```
--------------------------------
### Access custom component options
Source: https://vuejs.org/api/component-instance
Example of accessing custom options via $options within a component.
```js
const app = createApp({
customOption: 'foo',
created() {
console.log(this.$options.customOption) // => 'foo'
}
})
```
--------------------------------
### Vue Mixin Example
Source: https://vuejs.org/api/options-composition
Demonstrates how to use mixins to combine component options. Mixin hooks are called before the component's own hooks.
```js
const mixin = {
created() {
console.log(1)
}
}
createApp({
created() {
console.log(2)
},
mixins: [mixin]
})
```
--------------------------------
### Vue.js Reactive Object Example
Source: https://vuejs.org/api/reactivity-core
Demonstrates creating a reactive object and modifying its property. Changes to the reactive object trigger updates.
```javascript
const obj = reactive({ count: 0 })
obj.count++
```
--------------------------------
### Provide Static and Reactive Values in Vue
Source: https://vuejs.org/api/composition-api-dependency-injection
Use provide() to make values available to descendant components. It must be called synchronously during the component's setup phase.
```vue
```
--------------------------------
### Importing from npm packages
Source: https://vuejs.org/api/sfc-spec
External resources can be imported directly from installed npm packages using the src attribute.
```vue
```
--------------------------------
### Using a Local Custom Directive
Source: https://vuejs.org/api/options-misc
Example of using a locally registered custom directive 'v-focus' on an input element.
```html
```
--------------------------------
### Component Usage with Debounced Ref
Source: https://vuejs.org/api/reactivity-advanced
Example of using the `useDebouncedRef` composable within a Vue component's script setup and template.
```vue
```
--------------------------------
### Reactive Props Destructure Compilation Example
Source: https://vuejs.org/api/sfc-script-setup
Vue's compiler automatically prepends 'props.' to destructured variables from defineProps in
hello
```
--------------------------------
### Component Options: template
Source: https://vuejs.org/api/options-rendering
Defines a string template for the component. If the string starts with '#', it's treated as a query selector for an element's innerHTML. Ignored if `render` is present.
```APIDOC
## Component Options: template
### Description
A string template for the component. If the string starts with `#`, it will be used as a `querySelector` and use the selected element's `innerHTML` as the template string. This allows the source template to be authored using native `` elements. Ignored if the `render` option is also present.
### Type
```ts
interface ComponentOptions {
template?: string
}
```
### Details
A template provided via the `template` option will be compiled on-the-fly at runtime. It is only supported when using a build of Vue that includes the template compiler. The template compiler is **NOT** included in Vue builds that have the word `runtime` in their names, e.g. `vue.runtime.esm-bundler.js`.
If the root component of your application doesn't have a `template` or `render` option specified, Vue will try to use the `innerHTML` of the mounted element as the template instead.
:::warning Security Note
Only use template sources that you can trust. Do not use user-provided content as your template. See [Security Guide](/guide/best-practices/security#rule-no-1-never-use-non-trusted-templates) for more details.
:::
### See also
* [Dist file guide](https://github.com/vuejs/core/tree/main/packages/vue#which-dist-file-to-use)
```
--------------------------------
### Define Vue Component with Function Syntax (Composition API)
Source: https://vuejs.org/api/general
Use `defineComponent` with function syntax for Composition API components, requiring Vue 3.3+. It accepts a setup function and optional extra options.
```typescript
function defineComponent(
setup: ComponentOptions['setup'],
extraOptions?: ComponentOptions
): () => any
```
--------------------------------
### Inject Message in Setup Function
Source: https://vuejs.org/api/application
Injects the 'message' provided at the app level within a component's setup function. Requires 'inject' to be imported from 'vue'.
```javascript
import { inject } from 'vue'
export default {
setup() {
console.log(inject('message')) // 'hello'
}
}
```
--------------------------------
### Specify Teleport Target
Source: https://vuejs.org/api/built-in-components
Examples of targeting different DOM elements using selectors.
```vue-html
```
--------------------------------
### app.runWithContext()
Source: https://vuejs.org/api/application
Executes a callback with the current app as the injection context.
```APIDOC
## app.runWithContext()
### Description
Execute a callback with the current app as injection context. Supported in 3.3+.
### Parameters
#### Request Body
- **fn** (() => T) - Required - The callback function to execute.
```
--------------------------------
### Application Instance Methods
Source: https://vuejs.org/api/application
Methods available on a Vue application instance.
```APIDOC
## app.mount()
### Description
Mounts the application instance in a container element.
### Details
The argument can either be an actual DOM element or a CSS selector (the first matched element will be used). Returns the root component instance.
If the component has a template or a render function defined, it will replace any existing DOM nodes inside the container. Otherwise, if the runtime compiler is available, the `innerHTML` of the container will be used as the template.
In SSR hydration mode, it will hydrate the existing DOM nodes inside the container. If there are [mismatches](/guide/scaling-up/ssr#hydration-mismatch), the existing DOM nodes will be morphed to match the expected output.
For each app instance, `mount()` can only be called once.
### Example
```js
import { createApp } from 'vue'
const app = createApp(/* ... */)
app.mount('#app')
```
Can also mount to an actual DOM element:
```js
app.mount(document.body.firstChild)
```
## app.unmount()
### Description
Unmounts a mounted application instance, triggering the unmount lifecycle hooks for all components in the application's component tree.
## app.onUnmount()
### Description
Registers a callback to be called when the app is unmounted.
### Details
```ts
interface App {
onUnmount(callback: () => any): void
}
```
```
--------------------------------
### inject()
Source: https://vuejs.org/api/composition-api-dependency-injection
Injects a value provided by an ancestor component or the application. Must be called synchronously during setup().
```APIDOC
## inject()
### Description
Injects a value provided by an ancestor component or the application. If no value is found, it returns undefined unless a default value is provided.
### Parameters
- **key** (InjectionKey | string) - Required - The key to look for in the parent chain.
- **defaultValue** (T | () => T) - Optional - The default value to return if the key is not found.
- **treatDefaultAsFactory** (boolean) - Optional - Indicates if the second argument should be treated as a factory function.
```
--------------------------------
### app.config.performance
Source: https://vuejs.org/api/application
Enable component init, compile, render and patch performance tracing in the browser devtool performance/timeline panel. Only works in development mode.
```APIDOC
## app.config.performance
### Description
Set this to `true` to enable component init, compile, render and patch performance tracing in the browser devtool performance/timeline panel. Only works in development mode and in browsers that support the [performance.mark](https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark) API.
### Type
`boolean`
### See also
[Guide - Performance](/guide/best-practices/performance)
```
--------------------------------
### Identify identity hazards with markRaw
Source: https://vuejs.org/api/reactivity-advanced
Example illustrating potential identity hazards when mixing raw and proxied objects.
```js
const foo = markRaw({
nested: {}
})
const bar = reactive({
// although `foo` is marked as raw, foo.nested is not.
nested: foo.nested
})
console.log(foo.nested === bar.nested) // false
```
--------------------------------
### Create Vue Application Instance
Source: https://vuejs.org/api/application
Use `createApp` to create a new Vue application instance. Pass the root component as the first argument. An optional second argument can be used for root props.
```js
import { createApp } from 'vue'
const app = createApp({
/* root component options */
})
```
```js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
```
--------------------------------
### Application Creation API
Source: https://vuejs.org/api/application
APIs for creating new Vue application instances.
```APIDOC
## createApp()
### Description
Creates an application instance.
### Details
The first argument is the root component. The second optional argument is the props to be passed to the root component.
### Example
With inline root component:
```js
import { createApp } from 'vue'
const app = createApp({
/* root component options */
})
```
With imported component:
```js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
```
### See also
[Guide - Creating a Vue Application](/guide/essentials/application)
## createSSRApp()
### Description
Creates an application instance in [SSR Hydration](/guide/scaling-up/ssr#client-hydration) mode. Usage is exactly the same as `createApp()`.
```
--------------------------------
### beforeMount
Source: https://vuejs.org/api/options-lifecycle
Called right before the component is to be mounted. Reactive state is set up, but no DOM nodes have been created yet.
```APIDOC
## beforeMount
### Description
Called right before the component is to be mounted.
### Method
Options API Hook
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
### Details
When this hook is called, the component has finished setting up its reactive state, but no DOM nodes have been created yet. It is about to execute its DOM render effect for the first time. This hook is not called during server-side rendering.
```
--------------------------------
### h()
Source: https://vuejs.org/api/render-function
Creates virtual DOM nodes (vnodes).
```APIDOC
## h()
### Description
Creates virtual DOM nodes (vnodes). The first argument can be a string (native element) or a component definition.
### Parameters
- **type** (string | Component) - Required - The element type or component definition.
- **props** (object | null) - Optional - Props to be passed to the element or component.
- **children** (Children | Slot | Slots) - Optional - The children of the vnode.
### Response
- **VNode** (object) - The created virtual DOM node.
```
--------------------------------
### Get Current Effect Scope
Source: https://vuejs.org/api/reactivity-advanced
Retrieves the currently active effect scope. Returns undefined if no scope is active.
```ts
function getCurrentScope(): EffectScope | undefined
```
--------------------------------
### Merge props with mergeProps()
Source: https://vuejs.org/api/render-function
Example of merging multiple props objects with special handling for class, style, and event listeners.
```js
import { mergeProps } from 'vue'
const one = {
class: 'foo',
onClick: handlerA
}
const two = {
class: { bar: true },
onClick: handlerB
}
const merged = mergeProps(one, two)
/**
{
class: 'foo bar',
onClick: [handlerA, handlerB]
}
*/
```
--------------------------------
### Provide Per-Component State
Source: https://vuejs.org/api/options-composition
Shows how to use a function with the `provide` option to provide reactive state from component data.
```javascript
export default {
data() {
return {
msg: 'foo'
}
}
provide() {
return {
msg: this.msg
}
}
}
```
--------------------------------
### version
Source: https://vuejs.org/api/general
Exposes the current version of the Vue framework as a string.
```APIDOC
## version
### Description
Exposes the current version of Vue.
### Type
string
### Example
```js
import { version } from 'vue'
console.log(version)
```
```
--------------------------------
### resolveDirective()
Source: https://vuejs.org/api/render-function
Manually resolves a registered directive by its name. Similar to resolveComponent, it must be called within setup() or the render function.
```APIDOC
## resolveDirective()
### Description
For manually resolving a registered directive by name.
### Method
`resolveDirective(name: string): Directive | undefined`
### Details
Note: you do not need this if you can import the directive directly.
`resolveDirective()` must be called inside either `setup()` or the render function in order to resolve from the correct component context.
If the directive is not found, a runtime warning will be emitted, and the function returns `undefined`.
### See also
[Guide - Render Functions - Custom Directives](/guide/extras/render-function#custom-directives)
```
--------------------------------
### app.provide()
Source: https://vuejs.org/api/application
Provides a value that can be injected in all descendant components within the application.
```APIDOC
## app.provide()
### Description
Provide a value that can be injected in all descendant components within the application.
### Parameters
#### Request Body
- **key** (InjectionKey | symbol | string) - Required - The injection key.
- **value** (T) - Required - The value to provide.
```
--------------------------------
### Implement watch option in a component
Source: https://vuejs.org/api/options-state
Demonstrates various ways to use the watch option, including top-level property watching, method references, deep watching, nested paths, immediate execution, and arrays of callbacks.
```js
export default {
data() {
return {
a: 1,
b: 2,
c: {
d: 4
},
e: 5,
f: 6
}
},
watch: {
// watching top-level property
a(val, oldVal) {
console.log(`new: ${val}, old: ${oldVal}`)
},
// string method name
b: 'someMethod',
// the callback will be called whenever any of the watched object properties change regardless of their nested depth
c: {
handler(val, oldVal) {
console.log('c changed')
},
deep: true
},
// watching a single nested property:
'c.d': function (val, oldVal) {
// do something
},
// the callback will be called immediately after the start of the observation
e: {
handler(val, oldVal) {
console.log('e changed')
},
immediate: true
},
// you can pass array of callbacks, they will be called one-by-one
f: [
'handle1',
function handle2(val, oldVal) {
console.log('handle2 triggered')
},
{
handler: function handle3(val, oldVal) {
console.log('handle3 triggered')
}
/* ... */
}
]
},
methods: {
someMethod() {
console.log('b changed')
},
handle1() {
console.log('handle 1 triggered')
}
},
created() {
this.a = 3 // => new: 3, old: 1
}
}
```
--------------------------------
### data() Option
Source: https://vuejs.org/api/options-state
Defines the initial reactive state for a component instance.
```APIDOC
## data
### Description
A function that returns the initial reactive state for the component instance. The returned object is made reactive and proxied on the component instance.
### Parameters
- **vm** (ComponentPublicInstance) - Optional - The component instance, accessible when using an arrow function.
### Request Example
```js
export default {
data() {
return { a: 1 }
}
}
```
```
--------------------------------
### customRef Type Definition
Source: https://vuejs.org/api/reactivity-advanced
Defines the type for the customRef factory function and its arguments (track, trigger) and return object (get, set).
```typescript
function customRef(factory: CustomRefFactory): Ref
type CustomRefFactory = {
track: () => void,
trigger: () => void
} => {
get: () => T,
set: (value: T) => void
}
```
--------------------------------
### Optional Inject with Default
Source: https://vuejs.org/api/options-composition
Demonstrates how to make an injection optional by providing a default value.
```javascript
const Child = {
inject: {
foo: { default: 'foo' }
}
}
```
--------------------------------
### Shallow ref usage example
Source: https://vuejs.org/api/reactivity-advanced
Demonstrates how mutations to the inner properties of a `shallowRef` do not trigger reactivity, while reassigning the `.value` does. This is typical for performance-sensitive scenarios.
```javascript
const state = shallowRef({ count: 1 })
// does NOT trigger change
state.value.count = 2
// does trigger change
state.value = { count: 2 }
```
--------------------------------
### onBeforeMount()
Source: https://vuejs.org/api/composition-api-lifecycle
Registers a hook to be called right before the component is to be mounted. At this point, reactive state is set up, but no DOM nodes have been created yet.
```APIDOC
## onBeforeMount()
### Description
Registers a hook to be called right before the component is to be mounted.
### Method
N/A (Function Call)
### Endpoint
N/A
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
N/A
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```