Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue 3 Composition API

Vue 3 Composition API

Vue 3's Composition API is mainly used to improve the reusability of code logic in large components.

As traditional components grow in business complexity, the code volume keeps increasing, and the whole code logic becomes hard to read and understand.

The place where Vue 3 uses the Composition API is setup.

In setup, we can group parts of the code by logical concern, then extract logic fragments and share code with other components. Therefore, the Composition API allows us to write more organized code.

Compare the following two pieces of code:

1. Traditional Component

2. Composition API


setup Component

The setup() function executes before the component is created (created()).

The setup() function receives two parameters: props and context.

The first parameter, props, is reactive and is updated when a new prop is passed in.

The second parameter, context, is a plain JavaScript object — a context object that exposes other values that may be useful in setup.

Note:You should avoid using this in setup, because it will not find the component instance. setup is called before data properties, computed properties, or methods are resolved, so they cannot be accessed in setup.

The following example uses the Composition API to define a counter:

Example (src/APP.vue)

In Vue 3.0, we can make any reactive variable work anywhere via a new ref function, as shown below:

import { ref } from 'vue'



let count = ref(0);

The ref() function creates a reactive data object based on a given value; the return value is an object containing only a .value property.

Inside the setup() function, the reactive data created by ref() returns an object, so you need to use .value to access it.

Example

import

{

ref

}

from

'vue'

const

counter

=

ref

(

0

)

console.

log

(

counter

)

// { value: 0 }

console.

log

(

counter.

value

)

// 0

counter.

value

++

console.

log

(

counter.

value

)

// 1


Vue Composition API Lifecycle Hooks

In Vue 2, we implemented lifecycle hook functions as follows:

Example

export

default

{

  beforeMount

(

)

{

    console.

log

(

'V2 beforeMount!'

)

 

}

,

  mounted

(

)

{

    console.

log

(

'V2 mounted!'

)

 

}

}

;

In Vue 3's Composition API, lifecycle hook functions can be implemented inside setup() using functions with the on prefix:

Example

import

{

onBeforeMount

,

onMounted

}

from

'vue'

;

export

default

{

  setup

(

)

{

    onBeforeMount

(

(

)

=>

{

      console.

log

(

'V3 beforeMount!'

)

;

   

}

)

    onMounted

(

(

)

=>

{

      console.

log

(

'V3 mounted!'

)

;

   

}

)

 

}

}

;

The following table is the mapping between the Options API and the Composition API, including how to call lifecycle hooks inside setup():

Vue2 Options-based API Vue Composition API
beforeCreate setup()
created setup()
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
errorCaptured onErrorCaptured

Because setup runs around the beforeCreate and created lifecycle hooks, there is no need to explicitly define them. In other words, any code written in those hooks should be written directly in the setup function.

These functions accept a callback function that is executed when the hook is invoked by the component:

Example

setup

(

)

{

...

   

// When the component is mounted, we use the onMounted hook to log some messages

    onMounted

(

(

)

=>

console.

log

(

'component mounted!'

)

)

;

...

}


Template Refs

When using the Composition API, the concepts of reactive refs and template refs are unified.

To obtain a reference to an element or component instance in the template, we can declare a ref as usual and return it from setup():

Example

<

template

<

div ref

=

"root"

This is a root element

div

template

<script import{ref,onMounted}from'vue' export default{setup(){const root=ref(null)onMounted(()=>{>

// The DOM element will be assigned to the ref after the initial render

        console.

log

(

root.

value

)

//

This is a root element

     

}

)

     

return

{

        root

     

}

   

}

 

}

script

In the example above, we expose root in the render context and bind it to the div as its ref via ref="root".

A ref used as a template behaves like any other ref: they are reactive and can be passed to (or returned from) composable functions.

Usage in v-for

Composition API template refs have no special handling when used inside v-for. Instead, use function refs to perform custom handling:

Example

<

template

<

div v

for

=

"(item, i) in list"

:

ref

=

"el => { if (el) divs[i] = el }"

   

{

{

item

}

}

 

div

template

<script import{ref,reactive,onBeforeUpdate}from'vue' export default{setup(){const list=reactive([1,2,3])const divs=ref([])>

// Ensure the ref is reset before each update

      onBeforeUpdate

(

(

)

=>

{

        divs.

value

=

[

]

     

}

)

     

return

{

        list

,

        divs

     

}

   

}

 

}

script

Watching Template Refs

Watching template ref changes can replace the lifecycle hooks demonstrated in the previous example.

But a key difference from lifecycle hooks is that watch() and watchEffect() run with side effects before the DOM is mounted or updated, so when the watcher runs, the template ref has not yet been updated.

Example

<

template

<

div ref

=

"root"

This is a root element

div

template

<script import{ref,watchEffect}from'vue' export default{setup(){const root=ref(null)watchEffect(()=>{>

// This side effect runs before the DOM update, so the template ref does not yet hold a reference to the element.

        console.

log

(

root.

value

)

// => null

     

}

)

     

return

{

        root

     

}

   

}

 

}

script

Therefore, a watcher using a template ref should be defined with the flush: 'post' option, which runs the side effect after the DOM update, ensuring the template ref stays in sync with the DOM and references the correct element.

Example

<

template

<

div ref

=

"root"

This is a root element

div

template

<script import{ref,watchEffect}from'vue' export default{setup(){const root=ref(null)watchEffect(()=>{>

        console.

log

(

root.

value

)

// =>

This is a root element

     

}

,

     

{

        flush

:

'post'

     

}

)

     

return

{

        root

     

}

   

}

 

}

script


API Reference

No. API and Description Example
1 setup()
The entry function in a component's Composition API, called when the component is instantiated, used to define reactive data and methods. export default { setup() { const count = ref(0); return { count }; } }
2 ref()
Creates a reactive reference used to wrap a primitive type or object. const count = ref(0)
3 computed()
Creates a value computed from other reactive data. const doubledCount = computed(() => count.value * 2)
4 reactive()
Creates a reactive object, suitable for objects or arrays. const state = reactive({ count: 0 })
5 readonly()
Creates read-only reactive data that cannot be modified. const state = readonly({ count: 0 })
6 watchEffect()
Creates a reactive side effect that automatically tracks its related reactive dependencies. watchEffect(() => { console.log(count.value) })
7 watchPostEffect()
A side effect triggered after the DOM updates. watchPostEffect(() => { console.log('Post effect') })
8 watchSyncEffect()
Executes a side effect synchronously when reactive dependencies change. watchSyncEffect(() => { console.log('Synchronized effect') })
9 watch()
Used to watch changes in reactive data; can specify a particular reactive data or computed property. watch(count, (newCount) => { console.log(newCount) })
10 onWatcherCleanup()
Cleans up a watcher, called when the watched data is no longer needed. watch(count, () => {}, onWatcherCleanup(() => { console.log('cleaned up') }))
11 isRef()
Checks whether a value is ref type. isRef(count)
12 unref()
Unwraps a ref value. unref(count)
13 toRef()
Creates a reactive reference extracted from an object. const countRef = toRef(state, 'count')
14 toValue()
Unwraps ref or reactive typed values. toValue(count)
15 toRefs()
Converts each property of a reactive object into an independent ref. const { count } = toRefs(state)
16 isProxy()
Checks whether an object is a Vue proxy object. isProxy(state)
17 isReactive()
Checks whether an object is a reactive object. isReactive(state)
18 isReadonly()
Checks whether an object is a read-only reactive object. isReadonly(state)
19 shallowRef()
Creates a shallow ref, making only the object's first-level properties reactive. const state = shallowRef({ count: 0 })
20 triggerRef()
Force a re-render of ref 's update. triggerRef(count)
21 customRef()
Creates a custom reactive reference, allowing developers to define custom getters and setters. const count = customRef((track, trigger) => { let value = 0; return { get: () => value, set: (val) => { value = val; trigger() } } })
22 shallowReactive()
Creates a shallow reactive object where only the object's first-level properties are reactive. const state = shallowReactive({ count: 0 })
23 shallowReadonly()
Creates a shallow read-only reactive object where only the object's first-level properties are read-only. const state = shallowReadonly({ count: 0 })
24 toRaw()
Retrieves the raw object of a proxy object. const rawState = toRaw(state)
25 markRaw()
Marks an object as non-proxyable; Vue will skip reactivity processing for this object. const obj = markRaw({ count: 0 })
26 effectScope()
Creates a new effect scope for managing side effects. const scope = effectScope()
27 getCurrentScope()
Gets the current effect scope. const scope = getCurrentScope()
28 onScopeDispose()
Executes a cleanup function when the effect scope is destroyed. onScopeDispose(() => { console.log('Scope disposed') })
29 onMounted()
Lifecycle hook called when the component finishes mounting. onMounted(() => { console.log('Component mounted') })
30 onUpdated()
Lifecycle hook called when the component updates. onUpdated(() => { console.log('Component updated') })
31 onUnmounted()
Lifecycle hook called when the component is unmounted. onUnmounted(() => { console.log('Component unmounted') })
32 onBeforeMount()
Lifecycle hook called before the component mounts. onBeforeMount(() => { console.log('Before mount') })
33 onBeforeUpdate()
Lifecycle hook called before the component updates. onBeforeUpdate(() => { console.log('Before update') })
34 onBeforeUnmount()
Lifecycle hook called before the component unmounts. onBeforeUnmount(() => { console.log('Before unmount') })
35 onErrorCaptured()
Captures unhandled errors in the component tree. onErrorCaptured((err, instance, info) => { console.error(err) })
36 onRenderTracked()
Hook triggered when reactive data is tracked during component rendering. onRenderTracked((event) => { console.log(event) })
37 onRenderTriggered()
Hook triggered when reactive data changes during component rendering. onRenderTriggered((event) => { console.log(event) })
38 onActivated()
Lifecycle hook called when the component is activated (used for keep-alive components). onActivated(() => { console.log('Component activated') })
39 onDeactivated()
Lifecycle hook called when the component is deactivated (used for keep-alive components). onDeactivated(() => { console.log('Component deactivated') })
40 onServerPrefetch()
the hook for prefetching data during server-side rendering. onServerPrefetch(async () => { await fetchData() })
41 provide()
Passes dependencies down to descendant components. provide('key', value)
42 inject()
Injects dependencies from a parent or ancestor component. const value = inject('key')
43 hasInjectionContext()
Checks whether there is an injection context currently. hasInjectionContext()
44 useAttrs()
Gets all attributes of a component, including HTML features passed to it. const attrs = useAttrs()
45 useSlots()
Gets the slot content of a component. const slots = useSlots()
46 useModel()
Gets the current component's v-model bound value. const modelValue = useModel()
47 useTemplateRef()
Gets references to elements in the template. const templateRef = useTemplateRef('elementId')
48 useId()
Gets a unique identifier. const uniqueId = useId()