Getting Started with Vue 3 Composition API
1. Project Initialization
- Install Vue CLI 3:
npm install -g @vue/cli - Create a new project:
vue create my-project - Enstall the Composition API in the project:
npm install @vue/composition-api --save - Set up the Composition API in
main.jsusingVue.use():
import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';
Vue.use(VueCompositionApi);
2. The setup Function
The setup function executes after beforeCreate and before created.
It accepts two parameters: setup(props, context) {}
props: Parameters passed from external sources.context: A context object similar tothisin Vue 2, providing access to properties likecontext.attrs,context.emit, andcontext.refs. Note thatthiscannot be used insidesetup.
Advantages of setup:
Instead of declaring multiple options such as data(), methods, created, mounted, and watch, you can now consolidate all logic within the setup function. This approach enhances modularity by grouping related state and methods together, reducing redundancy when creating new components.
3. ref and reactive
ref: Theref()function creates a reactive data object from a given value, e.g.,const counter = ref(0). Access the value viacounter.value.reactive: Creates a reactive data object, similar to the object returned bydata()in Vue 2, e.g.,const state = reactive({ counter: 0 }). Access values viastate.counter.
Why have two ways to create reactivity? Vue's team designed these APIs to accommodate different coding styles. For example,
refis akin to direct variable declarations (e.g.,let x = 1), whilereactiveis like storing values in an object (e.g.,let state = { x: 1 }).
Important: When using the spread operator (...) on a reactive object, the result loses reactiivty. Use ...toRefs(state) to convert it to ref objects.
4. isRef and toRefs
isRef(): Checks if a value is arefobject.toRefs(): Converts areactiveobject intorefobjects. This is useful when returning multiple reactive objects fromsetup:
setup() {
const state = reactive({
counter: 0
});
const myRef = ref(1);
return {
...toRefs(state),
myRef
};
}
Why use toRefs? A reactive object must be returned as state directly, not as { state }. This function facilitates returning multiple reactive objects. For simplicity, using ref directly is often recommended.
5. computed and watch
In Vue 3, computed and watch are declared within the setup function.
computed:
setup() {
const counter = ref(1);
const incrementedCounter = computed(() => counter.value + 1);
return {
counter,
incrementedCounter
};
}
watch:
const counter = ref(1);
watch(() => console.log(counter.value));
6. Lifecycle Hooks
→ usebeforeCreatesetup()→ usecreatedsetup()beforeMount→onBeforeMountmounted→onMountedbeforeUpdate→onBeforeUpdateupdated→onUpdatedbeforeDestroy→onBeforeUnmountdestroyed→onUnmountederrorCaptured→onErrorCaptured
Two new debugging hooks are added:
onRenderTrackedonRenderTriggered
Example:
export default {
onRenderTriggered(event) {
debugger;
// Inspect which dependency triggers re-rendering
}
};
7. provide and inject
provide() and inject() enable data passing between nested components, usable only within setup(). Use provide() in a parent component to pass data down, and inject() in child components to receive it.
Parenet component:
setup() {
const counter = ref(1);
provide('counter', counter); // Pass counter to child
},
Child component:
setup() {
const counter = inject('counter'); // Receive counter
},