@vue/composition-api
Provide logic composition capabilities for Vue.
Last updated 2 years ago by antfu .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ gnpm install @vue/composition-api 
SYNC missed versions from official npm registry.

@vue/composition-api

Vue 2 plugin for Composition API

npm GitHub Workflow Status Minzipped size

English | 中文Composition API Docs

⚠️ With the release of Vue 2.7, which has Composition API built-in, you no longer need this plugin. Thereby this plugin has entered maintenance mode and will only support Vue 2.6 or earlier. This project will reach End of Life by the end of 2022.

Installation

NPM

npm install @vue/composition-api
# or
yarn add @vue/composition-api

You must install @vue/composition-api as a plugin via Vue.use() before you can use the Composition API to compose your component.

import Vue from 'vue'
import VueCompositionAPI from '@vue/composition-api'

Vue.use(VueCompositionAPI)
// use the APIs
import { ref, reactive } from '@vue/composition-api'

:bulb: When you migrate to Vue 3, just replacing @vue/composition-api to vue and your code should just work.

CDN

Include @vue/composition-api after Vue and it will install itself automatically.

<script src="https://cdn.jsdelivr.net/npm/vue@2.6"></script>
<script src="https://cdn.jsdelivr.net/npm/@vue/composition-api@1.7.1"></script>

@vue/composition-api will be exposed to global variable window.VueCompositionAPI.

const { ref, reactive } = VueCompositionAPI

TypeScript Support

TypeScript version >4.2 is required

To let TypeScript properly infer types inside Vue component options, you need to define components with defineComponent

import { defineComponent } from '@vue/composition-api'

export default defineComponent({
  // type inference enabled
})

JSX/TSX

JSX is now officially supported on vuejs/jsx. You can enable it by following this document. A community maintained version can be found at babel-preset-vca-jsx by @luwanquan.

To support TSX, create a declaration file with the following content in your project.

// 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;
    }
  }
}

SSR

Even if there is no definitive Vue 3 API for SSR yet, this plugin implements the onServerPrefetch lifecycle hook that allows you to use the serverPrefetch hook found in the classic API.

import { onServerPrefetch } from '@vue/composition-api'

export default {
  setup(props, { ssrContext }) {
    const result = ref()

    onServerPrefetch(async () => {
      result.value = await callApi(ssrContext.someId)
    })

    return {
      result,
    }
  }
}

Browser Compatibility

@vue/composition-api supports all modern browsers and IE11+. For lower versions IE you should install WeakMap polyfill (for example from core-js package).

Limitations

:white_check_mark: Support     :x: Not Supported

Ref Unwrap

<summary> ❌ Should NOT use ref in a plain object when working with Array </summary>
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
const b = reactive({
  list: [
    {
      count: ref(0), // no unwrap!!
    },
  ],
})

// no unwrap for `count`, `.value` is required
b.list[0].count.value === 0 // true
<summary> ✅ Should always use ref in a reactive when working with Array </summary>
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

Template Refs

<summary> ✅ String ref && return it from setup() </summary>
<template>
  <div ref="root"></div>
</template>

<script>
  export default {
    setup() {
      const root = ref(null)

      onMounted(() => {
        // the DOM element will be assigned to the ref after initial render
        console.log(root.value) // <div/>
      })

      return {
        root,
      }
    },
  }
</script>
<summary> ✅ String ref && return it from setup() && Render Function / JSX </summary>
export default {
  setup() {
    const root = ref(null)

    onMounted(() => {
      // the DOM element will be assigned to the ref after initial render
      console.log(root.value) // <div/>
    })

    return {
      root,
    }
  },
  render() {
    // with JSX
    return () => <div ref="root" />
  },
}
<summary> ❌ Function ref </summary>
<template>
  <div :ref="el => root = el"></div>
</template>

<script>
  export default {
    setup() {
      const root = ref(null)

      return {
        root,
      }
    },
  }
</script>
<summary> ❌ Render Function / JSX in setup() </summary>
export default {
  setup() {
    const root = ref(null)

    return () =>
      h('div', {
        ref: root,
      })

    // with JSX
    return () => <div ref={root} />
  },
}
<summary> ⚠️ $refs accessing workaround </summary>

:warning: Warning: The SetupContext.refs won't exist in Vue 3.0. @vue/composition-api provide it as a workaround here.

If you really want to use template refs in this case, you can access vm.$refs via SetupContext.refs

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) // <div/>
    })

    return () =>
      h('div', {
        ref: 'root',
      })

    // with JSX
    return () => <div ref="root" />
  },
}

Reactive

<summary> ⚠️ reactive() mutates the original object </summary>

reactive uses Vue.observable underneath which will mutate the original object.

:bulb: In Vue 3, it will return an new proxy object.

<summary> ⚠️ set and del workaround for adding and deleting reactive properties </summary>

⚠️ Warning: set and del do NOT exist in Vue 3. We provide them as a workaround here, due to the limitation of Vue 2.x reactivity system.

In Vue 2, you will need to call set to track new keys on an object(similar to Vue.set but for reactive objects created by the Composition API). In Vue 3, you can just assign them like normal objects.

Similarly, in Vue 2 you will need to call del to ensure a key deletion triggers view updates in reactive objects (similar to Vue.delete but for reactive objects created by the Composition API). In Vue 3 you can just delete them by calling delete foo.bar.

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')

Watch

<summary> ❌ onTrack and onTrigger are not available in WatchOptions </summary>
watch(() => {
    /* ... */
}, {
  immediate: true,
  onTrack() {}, // not available
  onTrigger() {}, // not available
})

createApp

<summary> ⚠️ createApp() is global </summary>

In Vue 3, createApp() is introduced to provide context(plugin, components, etc.) isolation between app instances. Due the the design of Vue 2, in this plugin, we provide createApp() as a forward compatible API which is just an alias of the global.

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.use('Bar', Bar)

createElement / h

<summary> ⚠️ createElement / h workaround </summary>

createElement / h in Vue 2 is only accessable in render() function. To use it outside of render(), you can explicitly bind a component instance to it.

:warning: Warning: This ability is provided as a workaround Vue 2, it's not part of the Vue 3 API.

import { h as _h } from '@vue/composition-api'

export default {
  setup() {
    const vm = getCurrentInstance()
    const h = _h.bind(vm)

    return () =>
      h('div', {
        ref: 'root',
      })
  },
}

shallowReadonly

<summary> ⚠️ shallowReadonly() will create a new object and with the same root properties, new properties added will not be readonly or reactive. </summary>

:bulb: In Vue 3, it will return an new proxy object.

readonly

<summary> ⚠️ readonly() provides only type-level readonly check. </summary>

readonly() is provided as API alignment with Vue 3 on type-level only. Use isReadonly() on it or it's properties can not be guaranteed.

props

<summary> ⚠️ toRefs(props.foo) will incorrectly warn when accessing nested levels of props.
    ⚠️ isReactive(props.foo) will return false. </summary>
defineComponent({
  setup(props) {
    const { bar } = toRefs(props.foo) // it will `warn`

    // use this instead
    const { foo } = toRefs(props)
    const a = foo.value.bar
  }
})

computed().effect

<summary> ⚠️ computed() has a property effect set to true instead of a ReactiveEffect<T>. </summary>

Due to the difference in implementation, there is no such concept as a ReactiveEffect in @vue/composition-api. Therefore, effect is merely true to enable differentiating computed from refs:

function isComputed<T>(o: ComputedRef<T> | unknown): o is ComputedRef<T>
function isComputed(o: any): o is ComputedRef {
  return !!(isRef(o) && o.effect)
}

Missing APIs

The following APIs introduced in Vue 3 are not available in this plugin.

  • onRenderTracked
  • onRenderTriggered
  • isProxy

Reactive APIs in data()

<summary> ❌ Passing ref, reactive or other reactive apis to data() would not work. </summary>
export default {
  data() {
    return {
      // will result { a: { value: 1 } } in template
      a: ref(1),
    }
  },
}

emits Options

<summary> ❌ emits option is provided in type-level only, in order to align with Vue 3's type interface. Does NOT have actual effects on the code. </summary>
defineComponent({
  emits: {
    // has no effects
    submit: (eventOption) => {
      if (...) {
        return true
      } else {
        console.warn('Invalid submit event payload!')
        return false
      }
    }
  }
})

Performance Impact

Due the the limitation of Vue2's public API. @vue/composition-api inevitably introduces some performance overhead. Note that in most scenarios, this shouldn't be the source of performance issues.

You can check the benchmark results for more details.

Current Tags

  • 1.7.1                                ...           latest (2 years ago)
  • 1.1.0                                ...           next (3 years ago)

104 Versions

  • 1.7.1                                ...           2 years ago
  • 1.7.0                                ...           2 years ago
  • 1.6.3                                ...           2 years ago
  • 1.6.2                                ...           3 years ago
  • 1.6.1                                ...           3 years ago
  • 1.6.0                                ...           3 years ago
  • 1.5.0                                ...           3 years ago
  • 1.4.9                                ...           3 years ago
  • 1.4.8                                ...           3 years ago
  • 1.4.7                                ...           3 years ago
  • 1.4.6                                ...           3 years ago
  • 1.4.5                                ...           3 years ago
  • 1.4.4                                ...           3 years ago
  • 1.4.3                                ...           3 years ago
  • 1.4.2                                ...           3 years ago
  • 1.4.1                                ...           3 years ago
  • 1.4.0                                ...           3 years ago
  • 1.4.0-beta.0                                ...           3 years ago
  • 1.3.3                                ...           3 years ago
  • 1.3.1                                ...           3 years ago
  • 1.3.0                                ...           3 years ago
  • 1.2.4                                ...           3 years ago
  • 1.2.3                                ...           3 years ago
  • 1.2.2                                ...           3 years ago
  • 1.2.1                                ...           3 years ago
  • 1.2.0                                ...           3 years ago
  • 1.1.5                                ...           3 years ago
  • 1.1.4                                ...           3 years ago
  • 1.1.3                                ...           3 years ago
  • 1.1.2                                ...           3 years ago
  • 1.1.1                                ...           3 years ago
  • 1.1.0                                ...           3 years ago
  • 1.1.0-beta.7                                ...           3 years ago
  • 1.1.0-beta.6                                ...           3 years ago
  • 1.0.6                                ...           3 years ago
  • 1.1.0-beta.5                                ...           3 years ago
  • 1.0.5                                ...           3 years ago
  • 1.1.0-beta.4                                ...           3 years ago
  • 1.0.4                                ...           3 years ago
  • 1.1.0-beta.3                                ...           3 years ago
  • 1.0.3                                ...           3 years ago
  • 1.1.0-beta.2                                ...           3 years ago
  • 1.1.0-beta.1                                ...           3 years ago
  • 1.0.2                                ...           3 years ago
  • 1.0.1                                ...           3 years ago
  • 1.0.0                                ...           3 years ago
  • 1.0.0-rc.14                                ...           3 years ago
  • 1.0.0-rc.13                                ...           3 years ago
  • 1.0.0-rc.12                                ...           3 years ago
  • 1.0.0-rc.11                                ...           4 years ago
  • 1.0.0-rc.10                                ...           4 years ago
  • 1.0.0-rc.9                                ...           4 years ago
  • 1.0.0-rc.8                                ...           4 years ago
  • 1.0.0-rc.7                                ...           4 years ago
  • 1.0.0-rc.6                                ...           4 years ago
  • 1.0.0-rc.5                                ...           4 years ago
  • 1.0.0-rc.4                                ...           4 years ago
  • 1.0.0-rc.3                                ...           4 years ago
  • 1.0.0-rc.2                                ...           4 years ago
  • 1.0.0-rc.1                                ...           4 years ago
  • 1.0.0-beta.26                                ...           4 years ago
  • 1.0.0-beta.25                                ...           4 years ago
  • 1.0.0-beta.24                                ...           4 years ago
  • 1.0.0-beta.23                                ...           4 years ago
  • 1.0.0-beta.22                                ...           4 years ago
  • 1.0.0-beta.21                                ...           4 years ago
  • 1.0.0-beta.20                                ...           4 years ago
  • 1.0.0-beta.19                                ...           4 years ago
  • 1.0.0-beta.18                                ...           4 years ago
  • 1.0.0-beta.17                                ...           4 years ago
  • 1.0.0-beta.16                                ...           4 years ago
  • 1.0.0-beta.15                                ...           4 years ago
  • 1.0.0-beta.14                                ...           4 years ago
  • 1.0.0-beta.13                                ...           4 years ago
  • 1.0.0-beta.12                                ...           4 years ago
  • 1.0.0-beta.11                                ...           4 years ago
  • 1.0.0-beta.10                                ...           4 years ago
  • 1.0.0-beta.9                                ...           4 years ago
  • 1.0.0-beta.8                                ...           4 years ago
  • 1.0.0-beta.7                                ...           4 years ago
  • 1.0.0-beta.6                                ...           4 years ago
  • 1.0.0-beta.5                                ...           4 years ago
  • 1.0.0-beta.4                                ...           4 years ago
  • 1.0.0-beta.3                                ...           4 years ago
  • 1.0.0-beta.2                                ...           4 years ago
  • 1.0.0-beta.1                                ...           4 years ago
  • 0.6.7                                ...           4 years ago
  • 0.6.6                                ...           4 years ago
  • 0.6.5                                ...           4 years ago
  • 0.6.4                                ...           4 years ago
  • 0.6.3                                ...           4 years ago
  • 0.6.2                                ...           5 years ago
  • 0.6.1                                ...           5 years ago
  • 0.6.0                                ...           5 years ago
  • 0.5.0                                ...           5 years ago
  • 0.4.0                                ...           5 years ago
  • 0.3.4                                ...           5 years ago
  • 0.3.3                                ...           5 years ago
  • 0.3.2                                ...           5 years ago
  • 0.3.1                                ...           5 years ago
  • 0.3.0                                ...           5 years ago
  • 0.2.1                                ...           5 years ago
  • 0.2.0                                ...           5 years ago
  • 0.1.0                                ...           5 years ago
Downloads
Today 0
This Week 0
This Month 0
Last Day 0
Last Week 0
Last Month 0
Dependencies (0)
None
Dev Dependencies (22)
Dependents (1)

Copyright 2013 - present © cnpmjs.org | Home |