SoFunction
Updated on 2025-04-04

Deeply understand the implementation of Vue3 combination API

Benefits of Combined APIs

1. Better logical organization:

In the option API, component logic is written in chunks according to data, methods, computed, watch, etc. This separation may lead toCodes with the same function are scattered in different parts

Combined API viaCombine relevant logic together to make the code more compact and clear, especially in complex components, the way of organizing code is more natural.

2. Better logical reuse:

In the option API, if you want to reuse logic, mixin is usually used, but mixin has problems such as unclear scope and naming conflicts.

Combined API providesThe concept of composable (composable function), run extracts logic into independent functions, so that the reusability is stronger and the code is clearer.

3. Better type inference support:

Combined APIs better support TypeScript, especially within functions, the types of data and functions can be more explicitly inferred without the need for additional type definitions.

4. More flexible responsive system:

Combined APIs provide more flexible and responsive systems, such asRef and reactive can control the behavior of reactive data more intuitively

What life cycles does Vue3 have?

  • setup(): Start creating components, beforeCreate  and created , and create data and method
  • onBeforeMount(): Function executed before the component is mounted on a node
  • onMounted(): The function that the component is hung after completion;
  • onBeforeUpdate(): The function executed before the component updates;
  • onUpdated(): The function executed after the component update is completed;
  • onBeforeUnmount(): The function executed before the component is uninstalled;
  • onUnmounted(): The function executed after the component uninstallation is completed;
  • onActived(): Components contained in <keep-alive> will have two additional life cycle hook functions, which will be executed when activated;
  • onDeactivated(): For example, component A switches to component B, and component A disappears;
  • onErrorCaptured(): Activates the hook function when an exception from a descendant component is caught.

and compare

vue2           ------->      vue3
 
beforeCreate   -------->      setup(()=>{})
created        -------->      setup(()=>{})
beforeMount    -------->      onBeforeMount(()=>{})
mounted        -------->      onMounted(()=>{})
beforeUpdate   -------->      onBeforeUpdate(()=>{})
updated        -------->      onUpdated(()=>{})
beforeDestroy  -------->      onBeforeUnmount(()=>{})
destroyed      -------->      onUnmounted(()=>{})
activated      -------->      onActivated(()=>{})
deactivated    -------->      onDeactivated(()=>{})
errorCaptured  -------->      onErrorCaptured(()=>{})

The difference between watch and watchEffect?

Watch is used to listen for changes in specific responsive data and execute callback functions when the data changes. Here is an example of using watch:

import { ref, watch } from 'vue';
 
const count = ref(0);
 
watch(count, (newValue, oldValue) =&gt; {
  (`Count changed from ${oldValue} to ${newValue}`);
  // Perform some side effects, such as sending API requests, updating other statuses, etc.});
 
// Changing the count value will trigger the callback of the watch++;
  • watch accepts two parameters. The first parameter is the responsive value or computed property to be listened to (can be ref, property of a reactive object, or result of computed), and the second parameter is the callback function.
  • The callback function is called when the listened value changes, and it receives the new value and the old value as parameters.
  • If you want to listen deeply on the changes of objects or arrays, you can add a third parameter to the watch and configure the object, such as {deep:true}

watchEffect is a function that executes immediately and continuously listens to its internal dependencies. It re-executes every time the responsive value it depends on.

import { ref, watchEffect } from 'vue';
 
const count = ref(0);
const message = ref('Initial Message');
 
watchEffect(() =&gt; {
  (`Count is ${}, and message is ${}`);
  // Perform some side effects based on the values ​​of count and message});
 
// Changing the count or message value will trigger the re-execution of watchEffect++;
 = 'Updated Message';

Detailed explanation:

  • watchEffect does not need to specify the specific value of the listener, it automatically tracks all responsive dependencies involved in its internal expression.
  • When the watchEffect is called, it executes immediately and records a snapshot of the internal dependency, after which it executes again whenever the dependency changes.
  • If you want to stop listening, you can return a cleanup function, such as cleaning side effects when component unloading.

Comparison between watch and watchEffect

watch

  • Watch explicitly specifies dependent data, and executes callback functions when dependent data is updated.
  • Lazy lazy will not be executed when the page is displayed for the first time, and will only be executed when the data changes (it can become non-lazy when setting immediate: true, and the page will be executed for the first time it is loaded)
  • The original value can be obtained when monitoring the ref-defined ref data
  • It is necessary to indicate both the monitoring attributes and the monitoring callbacks

watchEffect

  • watchEffect automatically collects dependent data, and re-executes itself when the dependency data is updated.
  • Execute immediately, without laziness, the page will be executed for the first time it loads
  • The original value cannot be obtained, only the changed value can be obtained
  • It does not need to indicate which attribute to monitor. It is monitored which attribute is used in the monitored callback.

What is the difference between ref and reactive?

definition

reactive and ref are two reactive data binding methods in Vue 3. ref is suitable for simple reactive data, while reactive is suitable for reactive data of complex objects or arrays.

ref: Responsive data used to declare basic types or single variables.

The core of ref is that it wraps a value, and when this value changes, the view that depends on it will be rerendered.
Note: ref returns an object whose values ​​are accessed through the .value property.

const count = ref(0);
(); // 0
++;

reactive: Responsive data used to declare objects or arrays.

reactive is more suitable for handling complex data structures (objects or arrays). It returns a responsive object. When the object's properties are directly manipulated, the view will be automatically updated.

const state = reactive({
  name: 'Vue',
  age: 3
});
(); // 'Vue'
 = 4; // The view will be updated automatically

The main differences are as follows:

1. Different data types:

refUsed to wrap JavaScriptBasic types of data (such as strings, numbers, boolean values, etc.)

andreactiveCan be used to wrap JavaScriptComplex types of data such as objects and arrays

2. Different usage methods:

Ref needs to be created and used by using ref directives in templates and using ref functions in JavaScript code, while reactive needs to be wrapped and created by calling the provided reactive functions.

3. Different access methods:

For passingResponsive data created by ref function, we can pass.value attributeto access its actual value; and forReactive object created by reactive function, we canDirect access to its properties or call its methods

4. Different design concepts:

Ref is mainly to solve the responsive problem of single element/data, while reactive is to solve the responsive problem of complex data structures such as JavaScript objects and arrays.

<script setup>

<script setup>is a new syntactic sugar introduced by Vue 3, which is used to write components using a combination API. This syntax simplifies the use of the Composition API, making writing and organizing component logic more concise and intuitive.

Main features

  • Declarative<script setup>Provides a declarative way to use a combined API, reducing boilerplate code.
  • Automatic response:exist<script setup>Responsive references defined in   (e.g.refandreactive) and functions are automatically exposed to the template without returning objects.
  • Life cycle hook: Life cycle hook (such asonMountedonUpdatedetc.) can be imported and used directly without defining anonymous functions.
  • Module scope:exist<script setup>The variables and functions imported in automatically have module scope, reducing global naming conflicts.

Basic usage

<script setup>
import { ref, computed, onMounted } from 'vue';

const count = ref(0);
const doubledCount = computed(() =>  * 2);

onMounted(() => {
  ('Component is mounted');
});

function increment() {
  ++;
}
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Doubled Count: {{ doubledCount }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

Differences from <script>

  • No need to return an object:exist<script setup>In  , you do not need to return an object to expose responsive state, computed properties, and methods to the template.
  • Less code<script setup>Make the writing of components more concise and reduce boilerplate code.

Component definition

exist<script setup>In  , you can define the responsive state, compute properties, methods, and life cycle hooks of the component, just like in<script>The same way to use a combination API in the tag, but it is more concise.

Life cycle hook

<script setup>
import { onMounted } from 'vue';

onMounted(() => {
  ('Component is mounted');
});
</script>

This is the end of this article about in-depth understanding of Vue3 combination API. For more related Vue3 combination API content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!