Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
@vue/composition-api
Advanced tools
@vue/composition-api is a plugin that provides Vue 2.x users with the Composition API, which is a set of APIs that allows you to use Vue 3's reactivity system and component logic composition in Vue 2.x applications.
Reactive State
The `reactive` function is used to create a reactive state object. This allows you to manage state in a reactive manner, similar to Vue 3.
```javascript
import { reactive } from '@vue/composition-api';
export default {
setup() {
const state = reactive({ count: 0 });
return { state };
}
};
```
Computed Properties
The `computed` function is used to create computed properties that automatically update when their dependencies change.
```javascript
import { computed } from '@vue/composition-api';
export default {
setup() {
const state = reactive({ count: 0 });
const doubleCount = computed(() => state.count * 2);
return { state, doubleCount };
}
};
```
Watchers
The `watch` function is used to perform side effects in response to reactive state changes.
```javascript
import { watch } from '@vue/composition-api';
export default {
setup() {
const state = reactive({ count: 0 });
watch(() => state.count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`);
});
return { state };
}
};
```
Lifecycle Hooks
The `onMounted` and `onUnmounted` functions are used to register lifecycle hooks within the setup function.
```javascript
import { onMounted, onUnmounted } from '@vue/composition-api';
export default {
setup() {
onMounted(() => {
console.log('Component is mounted');
});
onUnmounted(() => {
console.log('Component is unmounted');
});
}
};
```
The `vue-function-api` package provides a similar Composition API for Vue 2.x. It allows you to use Vue 3's Composition API features in Vue 2.x applications. However, `@vue/composition-api` is the official plugin provided by the Vue team, making it more reliable and better supported.
The `vue-hooks` package offers a way to use hooks in Vue components, similar to React hooks. While it provides some similar functionality to the Composition API, it is not as comprehensive or integrated as `@vue/composition-api`.
@vue/composition-api
provides a way to use Vue 3.0
's Composition api in Vue 2.x
.
npm
npm install @vue/composition-api --save
yarn
yarn add @vue/composition-api
CDN
<script src="https://unpkg.com/@vue/composition-api/dist/vue-composition-api.umd.js"></script>
By using the global variable window.vueCompositionApi
You must install @vue/composition-api
via Vue.use()
before using other APIs:
import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';
Vue.use(VueCompositionApi);
After installing the plugin you can use the Composition API to compose your component.
This plugin requires TypeScript version >3.5.1. If you are using vetur, make sure to set vetur.useWorkspaceDependencies
to true
.
To let TypeScript properly infer types inside Vue component options, you need to define components with createComponent
:
import { createComponent } from '@vue/composition-api';
const Component = createComponent({
// type inference enabled
});
const Component = {
// this will NOT have type inference,
// because TypeScript can't tell this is options for a Vue component.
};
:rocket: An Example Repository with TS and TSX support is provided to help you start.
To support TSX, create a declaration file with 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 {
// tslint:disable no-empty-interface
interface Element extends VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends ComponentRenderProxy {}
interface ElementAttributesProperty {
$props: any; // specify the property name to use
}
interface IntrinsicElements {
[elem: string]: any;
}
}
}
Ref
UnwrapUnwrap
is not working with Array index.
ref
as a direct child of Array
:const state = reactive({
list: [ref(0)],
});
// no unwrap, `.value` is required
state.list[0].value === 0; // true
state.list.push(ref(1));
// no unwrap, `.value` is required
state.list[1].value === 1; // true
ref
in a plain object when working with Array
: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
ref
in a reactive
when working with Array
:const a = reactive({
count: ref(0),
});
const b = reactive({
list: [a],
});
// unwrapped
b.list[0].count === 0; // true
b.list.push(
reactive({
count: ref(1),
})
);
// unwrapped
b.list[1].count === 1; // true
watch()
APIonTrack
and onTrigger
are not available in WatchOptions
.
:white_check_mark: Support :x: Not Supported
:white_check_mark:
String ref && return it from setup()
:
<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>
:white_check_mark:
String ref && return it from setup()
&& Render Function / JSX:
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" />;
},
};
:x: Function ref:
<template>
<div :ref="el => root = el"></div>
</template>
<script>
export default {
setup() {
const root = ref(null);
return {
root,
};
},
};
</script>
:x: Render Function / JSX in setup()
:
export default {
setup() {
const root = ref(null);
return () =>
h('div', {
ref: root,
});
// with JSX
return () => <div ref={root} />;
},
};
If you really want to use template refs in this case, you can access vm.$refs
via SetupContext.refs
.
:warning: Warning: The
SetupContext.refs
won't exist inVue 3.0
.@vue/composition-api
provide it as a workaround here.
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" />;
},
};
You may also need to augment the SetupContext
when working with TypeScript:
import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';
Vue.use(VueCompositionApi);
declare module '@vue/composition-api/dist/component/component' {
interface SetupContext {
readonly refs: { [key: string]: Vue | Element | Vue[] | Element[] };
}
}
FAQs
Provide logic composition capabilities for Vue.
The npm package @vue/composition-api receives a total of 129,752 weekly downloads. As such, @vue/composition-api popularity was classified as popular.
We found that @vue/composition-api demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.