Vue Function API
vue-function-api
provides a way to use Vue3's Composition api in Vue2.x
.
Navigation
Installation
npm
npm install vue-function-api --save
yarn
yarn add vue-function-api
CDN
By using the global variable window.vueFunctionApi
Usage
You must explicitly install vue-function-api
via Vue.use()
:
;; Vue;
After installing the plugin you can use the Composition API to compose your component.
TypeScript
To let TypeScript properly infer types inside Vue component options, you need to define components with createComponent
:
; ; ;
Limitations
Ref
Unwrap
Unwrap
is not working with Array index.
ref
as a direct child of Array
:
Should not store const state = ;// no unwrap, `.value` is requiredstatelist0value === 0; // true statelist
ref
in a plain object when working with Array
:
Should not use const a = count: ;const b = ; // no unwrap for `count`, `.value` is requiredblist0countvalue === 0; // true
const b = ; // no unwrap for `count`, `.value` is requiredblist0countvalue === 0; // true
ref
in a reactive
when working with Array
:
Should always use const a = ;const b = ;// unwrappedblist0count === 0; // true blist;// unwrappedblist1count === 1; // true
watch()
API
onTrack
and onTrigger
are not available in WatchOptions
.
Template Refs
✅ Support ❌ Not Support
✅ String ref && return it from setup()
:
✅ String ref && return it from setup()
&& Render Function / JSX:
{ const root = ; ; return root ; } { // with JSX return <div ="root" />; };
❌ Function ref:
❌ Render Function / JSX in setup()
:
{ const root = ; return ; // with JSX return <div = />; };
If you really want to use template refs in this case, you can access vm.$refs
via SetupContext.refs
.
⚠️Warning: The
SetupContext.refs
won't existed inVue3.0
.Vue-function-api
provide it as a workaround here.
{ const refs = setupContextrefs; ; return ; // with JSX return <div ref="root" />; };
You may also need to augment the SetupContext
when wokring with TypeScript:
;; Vue.useVueFunctionApi; declare