### Installing Composition API Plugin with NPM Source: https://github.com/vuejs/composition-api/blob/main/README.md These commands demonstrate how to install the `@vue/composition-api` plugin using either npm or yarn package managers. This is the standard way to add the plugin to a Vue 2 project. ```bash npm install @vue/composition-api # or yarn add @vue/composition-api ``` -------------------------------- ### Defining Render Function in Setup (Current) - Vue Composition API - JavaScript Source: https://github.com/vuejs/composition-api/blob/main/CHANGELOG.md Illustrates the current method for returning a render function from the `setup` function in the Vue 2 Composition API. The returned render function no longer receives parameters, and `props` should be accessed directly within the `setup` scope. ```JavaScript export default { setup(props) { return () => h('div', prop.msg); }, }; ``` -------------------------------- ### Defining Render Function in Setup (Previous) - Vue Composition API - JavaScript Source: https://github.com/vuejs/composition-api/blob/main/CHANGELOG.md Demonstrates the previous signature for returning a render function from the `setup` function in the Vue 2 Composition API. In this older version, the returned render function received `props` as an argument. This signature is now deprecated. ```JavaScript export default { setup() { return props => h('div', prop.msg); }, }; ``` -------------------------------- ### Importing Composition API Functions Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet demonstrates how to import specific Composition API functions like `ref` and `reactive` from the `@vue/composition-api` package. These imported functions are then used within component `setup` options. ```javascript import { ref, reactive } from '@vue/composition-api' ``` -------------------------------- ### Retrieving String Template Ref Value in setup() Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet shows the corresponding ` ``` -------------------------------- ### Retrieving String Template Ref in setup() with Render Function / JSX Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet shows the component structure for using string template refs in a Render Function or JSX with the plugin. The ref is declared and returned from `setup`, and the Render Function/JSX uses the matching string name for the ref attribute. ```javascript export default { setup() { const root = ref(null) onMounted(() => { // the DOM element will be assigned to the ref after initial render console.log(root.value) //
}) return { root, } }, render() { // with JSX return () => }, } ``` -------------------------------- ### Including Composition API Plugin via CDN Source: https://github.com/vuejs/composition-api/blob/main/README.md This HTML snippet shows how to include the Vue 2 library and the `@vue/composition-api` plugin using CDN links. The plugin automatically installs itself when included after Vue. ```html ``` -------------------------------- ### Attempting to Use Ref Directly in JSX Render Function in setup() (Not Supported) Source: https://github.com/vuejs/composition-api/blob/main/README.md This JSX snippet shows an attempt to bind a ref directly (`ref={root}`) to an element within a render function defined inside the `setup` function. This method is not supported by the plugin for template refs. ```jsx return () => ``` -------------------------------- ### Accessing Template Refs via SetupContext.refs Workaround Source: https://github.com/vuejs/composition-api/blob/main/README.md This JSX/JavaScript snippet demonstrates a workaround in Vue 2 to access template refs within `setup` when using render functions or JSX. It involves using a string ref in the template/render function and accessing the corresponding element via `setupContext.refs`. ```jsx export default { setup(initProps, setupContext) { const refs = setupContext.refs onMounted(() => { // the DOM element will be assigned to the ref after initial render console.log(refs.root) // }) return () => h('div', { ref: 'root', }) // with JSX return () => }, } ``` -------------------------------- ### Using String Template Refs in Vue 2 Template Source: https://github.com/vuejs/composition-api/blob/main/README.md This HTML snippet demonstrates how to declare a template ref using a string value (`ref="root"`) directly in the template HTML element. This string name corresponds to a ref value returned from the `setup` function. ```html ``` -------------------------------- ### createApp() Global Nature in Vue 2 Workaround Source: https://github.com/vuejs/composition-api/blob/main/README.md This TypeScript snippet shows the `createApp` function provided by the plugin. In Vue 2, unlike Vue 3, `createApp` is just an alias for the global Vue instance, meaning plugin installations or component registrations (`app1.component`) affect the global `Vue` object. ```typescript const app1 = createApp(RootComponent1) app1.component('Foo', Foo) // equivalent to Vue.component('Foo', Foo) app1.use(VueRouter) // equivalent to Vue.use(VueRouter) const app2 = createApp(RootComponent2) app2.component('Bar', Bar) // equivalent to Vue.component('Bar', Bar) ``` -------------------------------- ### Demonstrating Ref Unwrap Limitation in Plain Objects within Reactive Array (2) Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet provides another example showing that a `ref` nested directly within a plain object inside a `reactive` array is not unwrapped. The `.value` property must be explicitly accessed. ```javascript const b = reactive({ list: [ { count: ref(0), // no unwrap!! }, ], }) // no unwrap for `count`, `.value` is required b.list[0].count.value === 0 // true ``` -------------------------------- ### Demonstrating Ref Unwrap Limitation in Plain Objects within Reactive Array (1) Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet illustrates a limitation where a `ref` inside a plain object within a `reactive` array does not get automatically unwrapped. Accessing the ref's value requires using the `.value` property. ```javascript const a = { count: ref(0), } const b = reactive({ list: [a], // `a.count` will not unwrap!! }) // no unwrap for `count`, `.value` is required b.list[0].count.value === 0 // true ``` -------------------------------- ### Using String Template Refs in Render Function / JSX Source: https://github.com/vuejs/composition-api/blob/main/README.md This JSX snippet illustrates declaring a template ref using a string (`ref="root"`) within a JSX render function. This method, along with returning the corresponding ref from `setup`, works correctly for accessing DOM elements. ```jsx () => ``` -------------------------------- ### Defining Emits Option (Vue Composition API, TypeScript) Source: https://github.com/vuejs/composition-api/blob/main/README.md This snippet shows the definition of the `emits` option within `defineComponent` when using the `@vue/composition-api` plugin. It emphasizes that this option is primarily for type-level alignment with Vue 3; any validation logic provided in the event handlers within `emits` (like the `submit` example) does not have actual runtime effect or validation functionality. ```TypeScript defineComponent({ emits: { // has no effects submit: (eventOption) => { if (...) { return true } else { console.warn('Invalid submit event payload!') return false } } } }) ``` -------------------------------- ### Initializing Composition API Plugin in Vue 2 Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet shows how to register the `@vue/composition-api` plugin with Vue using `Vue.use()`. This step is required before any Composition API functions can be used in the application. ```javascript import Vue from 'vue' import VueCompositionAPI from '@vue/composition-api' Vue.use(VueCompositionAPI) ``` -------------------------------- ### Using onServerPrefetch Hook for SSR Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet shows how to use the `onServerPrefetch` lifecycle hook provided by the plugin. This hook allows performing asynchronous data fetching during Server-Side Rendering (SSR) and is the Composition API equivalent of the classic `serverPrefetch` option. ```javascript import { onServerPrefetch } from '@vue/composition-api' export default { setup(props, { ssrContext }) { const result = ref() onServerPrefetch(async () => { result.value = await callApi(ssrContext.someId) }) return { result, } } } ``` -------------------------------- ### Accessing Composition API from Global Variable Source: https://github.com/vuejs/composition-api/blob/main/README.md This TypeScript snippet shows how to access Composition API functions like `ref` and `reactive` when the plugin is included via CDN. The APIs are exposed globally under `window.VueCompositionAPI`. ```typescript const { ref, reactive } = VueCompositionAPI ``` -------------------------------- ### Adding shim-tsx.d.ts for TSX Support Source: https://github.com/vuejs/composition-api/blob/main/README.md This TypeScript snippet provides the content for a `shim-tsx.d.ts` declaration file required to enable TSX support when using `@vue/composition-api`. This file defines the necessary global JSX interfaces. ```typescript // file: shim-tsx.d.ts import Vue, { VNode } from 'vue'; import { ComponentRenderProxy } from '@vue/composition-api'; declare global { namespace JSX { interface Element extends VNode {} interface ElementClass extends ComponentRenderProxy {} interface ElementAttributesProperty { $props: any; // specify the property name to use } interface IntrinsicElements { [elem: string]: any; } } } ``` -------------------------------- ### WatchOptions onTrack/onTrigger (Not Available) Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet demonstrates the `onTrack` and `onTrigger` options in `WatchOptions`, which are available in Vue 3 but **not** supported by the `@vue/composition-api` plugin in Vue 2. Attempting to use them will have no effect. ```javascript watch(() => { /* ... */ }, { immediate: true, onTrack() {}, // not available onTrigger() {}, // not available }) ``` -------------------------------- ### Defining Component with defineComponent for TypeScript Source: https://github.com/vuejs/composition-api/blob/main/README.md This TypeScript snippet illustrates the use of `defineComponent` from `@vue/composition-api` when defining Vue components. This wrapper is necessary to ensure proper type inference within the component options when using TypeScript. ```typescript import { defineComponent } from '@vue/composition-api' export default defineComponent({ // type inference enabled }) ``` -------------------------------- ### Declaring Props with createComponent and TypeScript - Vue Composition API - JavaScript Source: https://github.com/vuejs/composition-api/blob/main/CHANGELOG.md Shows how to declare component props using the `createComponent` helper from `@vue/composition-api` and TypeScript interfaces for type checking. It includes the necessary placeholder `props` definition for compatibility with the Vue 2 runtime. ```JavaScript import { createComponent, createElement as h } from '@vue/composition-api'; interface Props { msg: string; } const MyComponent = createComponent < Props > { props: { msg: {}, // required by vue 2 runtime }, setup(props) { return () => h('div', props.msg); }, }; ``` -------------------------------- ### JavaScript for Attempting Function Ref in Template (Not Supported) Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet provides the corresponding ` ``` -------------------------------- ### createElement / h Workaround by Binding Instance Source: https://github.com/vuejs/composition-api/blob/main/README.md This JSX/JavaScript snippet demonstrates a workaround to use the `createElement` (`h`) render function outside of a component's `render` option in Vue 2. It involves importing `h` from the plugin and explicitly binding the current component instance (`vm`) to it. ```jsx import { h as _h } from '@vue/composition-api' export default { setup() { const vm = getCurrentInstance() const h = _h.bind(vm) return () => h('div', { ref: 'root', }) }, } ``` -------------------------------- ### Declaring Ref Type - Vue Composition API - JavaScript Source: https://github.com/vuejs/composition-api/blob/main/CHANGELOG.md Demonstrates how to explicitly declare the type of a ref using TypeScript's generic syntax when initializing it with the `ref` function from the Vue Composition API. ```JavaScript const dateRef = ref < Date > new Date(); ``` -------------------------------- ### Attempting to Use Function Ref in Vue 2 Template (Not Supported) Source: https://github.com/vuejs/composition-api/blob/main/README.md This HTML snippet shows an attempt to use a function ref (`:ref="el => root = el"`) in a Vue 2 template with the Composition API plugin. This approach is not supported by the plugin for template refs. ```html ``` -------------------------------- ### Using Reactive APIs in Data Option (Vue Composition API, JavaScript) Source: https://github.com/vuejs/composition-api/blob/main/README.md This snippet illustrates a limitation where passing reactive API results like `ref(1)` directly into the `data()` option of a component using the `@vue/composition-api` plugin does not work as in Vue 3. The template will receive the raw ref object `{ value: 1 }` rather than the unwrapped value, requiring manual unwrapping or a different approach. ```JavaScript export default { data() { return { // will result { a: { value: 1 } } in template a: ref(1), } }, } ``` -------------------------------- ### Using set and del Workarounds for Reactive Objects in Vue 2 Source: https://github.com/vuejs/composition-api/blob/main/README.md This TypeScript snippet shows the `set` and `del` functions provided as workarounds for Vue 2's reactivity limitations with objects. `set` adds a new reactive property, and `del` removes a property while ensuring reactivity updates, similar to `Vue.set` and `Vue.delete` but for reactive objects created by the plugin. ```typescript import { reactive, set, del } from '@vue/composition-api' const a = reactive({ foo: 1 }) // add new reactive key set(a, 'bar', 1) // remove a key and trigger reactivity del(a, 'bar') ``` -------------------------------- ### Handling toRefs with Component Props (Vue Composition API, TypeScript) Source: https://github.com/vuejs/composition-api/blob/main/README.md This snippet demonstrates the correct and incorrect ways to use `toRefs` with component props when using the `@vue/composition-api` plugin. Applying `toRefs` directly to a nested prop (`props.foo`) will issue a warning. The recommended approach is to apply `toRefs` to the entire `props` object first and then access the property's value. ```TypeScript defineComponent({ setup(props) { const { bar } = toRefs(props.foo) // it will `warn` // use this instead const { foo } = toRefs(props) const a = foo.value.bar } }) ``` -------------------------------- ### Accessing Component Instance after API Change - JavaScript Source: https://github.com/vuejs/composition-api/blob/main/CHANGELOG.md This snippet illustrates a breaking change in the `getCurrentInstance` API. Previously, calling `getCurrentInstance()` directly returned the component instance (`vm`). Now, the instance is accessed via the `.proxy` property of the returned object. ```JavaScript const vm = getCurrentInstance() // becomes const vm = getCurrentInstance().proxy ``` -------------------------------- ### Demonstrating Correct Ref Unwrap in Reactive Objects within Reactive Array Source: https://github.com/vuejs/composition-api/blob/main/README.md This JavaScript snippet shows the correct way to achieve ref unwrapping within a reactive array by ensuring the nested objects containing refs are also made reactive using `reactive()`. This allows direct access to the ref's value without `.value`. ```javascript const a = reactive({ list: [ reactive({ count: ref(0), }), ] }) // unwrapped a.list[0].count === 0 // true a.list.push( reactive({ count: ref(1), }) ) // unwrapped a.list[1].count === 1 // true ``` -------------------------------- ### Declaring Complex Prop Types with PropType - Vue - TypeScript Source: https://github.com/vuejs/composition-api/blob/main/CHANGELOG.md Illustrates how to define complex prop types, such as objects with specific structures, using `PropType` within the `props` option when using `createComponent` or the standard Vue 3 component options. This enables accurate TypeScript type checking for nested data. ```TypeScript import { createComponent, PropType } from 'vue'; createComponent({ props: { options: (null as any) as PropType<{ msg: string }> }, setup(props) { props.options; // { msg: string } | undefined } }); ``` -------------------------------- ### Checking if a Value is Computed (Vue Composition API, TypeScript) Source: https://github.com/vuejs/composition-api/blob/main/README.md This function provides a type guard `isComputed` to check if a value is a computed ref within the `@vue/composition-api` plugin context. Due to implementation differences from Vue 3, it relies on checking if the value is a ref and if it has a truthy `effect` property, as `effect` is simply `true` instead of a `ReactiveEffect` instance. ```TypeScript function isComputed