### 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 ``` -------------------------------- ### 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 `