preface

This article will take an in-depth look at what composite API is, the usage of composite API in Vue3, precautions, and the way of value transfer between components through example code.

An introduction to the composite API

We know that data, listeners, computed properties, and functions in Vue2 are all set through options, the Option API.

exprot default {
    name: 'App'.computed: {},
    watach: {}}Copy the code

In Vue3, these options are made into hook functions, and a setup method is added to Vue3. The setup method appears in vUE objects in the form of options, but computed, watch, and so on in the above code become hook functions. Using the VUE structure and using it in setup, this allows us to encapsulate a function module into code, known as a composite API, which can be used quickly in Setup, as shown below:

import { watch, computed } from 'vue' 
const api = () = > {
    const a = ' '
    return { a }
}
export default { 
    name: 'App'.setup() { 
        watch(() = > { 
            // do something 
        }, () = > { 
            // do something 
        }) 
        const a = computed(() = > { 
            // do something 
        }) 
        return { ...api }
    } 
}
Copy the code

The whole point of setup is to make new composite apis available to users, and these apis can only be used within Setup.

Setup is performed after the props initialization and before the beforeCreate is executed. Therefore, this object cannot be used when the Vue instance is initialized. Instead of the beforeCreate and Created life cycles in Vue3, the other nine old life cycles can be used in Setup. Refer to the life cycle comparison table below:

Vue 2.0 Vue 3.0
beforeCreate setup()
created setup()
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
activated onActivated
deactivated onDeactivated
errorCaptured onErrorCaptured

Use the setup function in template

<template> 
    <div>{{ count }} {{ state.foo }}</div> 
</template> 
<script> 
import { ref, reactive } from 'vue' 
export default { 
    setup() { 
        const count = ref(0) 
        const state = reactive({ foo: 'bar' }) 
        return { count, state, } // expose to template}},</script>
Copy the code

As shown in the figure above, setup has two data variables, count and state wrapped in ref and reactive, which are then returned from setup. Variables returned from setup are exposed to Vue instances for use in templates. Of course, you can also return methods and functions.

Ref and Reactive here are the reactive methods in Vue3, which we will cover in the next section.