vue3’s composition API advanced syntax

Life cycle

In [options API], life cycle hooks are options exposed on the vue instance. We only need to call and use them.

In [composition API], we need to import the life cycle hook into the project before it can be used.

Pay attention to format changes

<script>
import { onMounted } from 'vue';
export default {
    setup(){
        onMounted(()=>{
            console.log("hello")
        })
    }
}
</script>

Here, beforecreate and created are replaced by the setup method itself, we will access 9 in setup life cycle:

onBeforeMount: Called before mounting, the rendering function render is called for the first time

onMounted: Called when the component is mounted

onBeforeUpdate: Called when the data is updated, which occurs before the virtual DOM is patched.

onUpdated: Called when the virtual DOM is re-rendered and patched due to data changes

onBeforeUnmount: Called before unmounting the component instance. The instance at this stage is still normal.

onActivated: Called when a component cached by keep-alive is activated

onDeactivated: Called when the component cached by keep-alive is deactivated

onErrorCaptured: Called when capturing an error from a descendant component. It has three parameters: the error object, the component instance where the error occurred, and a string containing error source information; this hook will return false to prevent changes. Errors continue to propagate upward

Example

<script>
import { onMounted } from 'vue';
export default {
    setup(){
        //Execute function immediately
        (function() {
          console.log("Execute immediately")
        })();
        function hello(){
            console.log("hello")
        }
        onMounted(()=>{
            console.log("life cycle")
        })
       hello()
      
        return{
            hello
        }
    }

}
</script>

Output order:

So the method defined inside the setup is executed before onmonuted

Execute function immediately:

Immediately Invoked Function Expression (IIFE) Immediately Invoked Function Expression (IIFE) is a JavaScript function that is executed immediately when it is defined. It uses anonymous function expressions (Function Expression) To encapsulate some code, and this code will be executed immediately after being defined.

The basic syntax of IIFE is as follows:

 (function() {
    //Write the code that needs to be executed here
  })();

Or you can use arrow function syntax:

(() => {
  //Write the code that needs to be executed here
})();

The main function of IIFE is to create a new scope to prevent variables from polluting the global scope. It can access variables in the outer scope, but cannot modify them. This makes IIFE ideal for modularizing and encapsulating JavaScript code.

provide

provide/inject in vue3 (provide injection)

With provide/inject, there is no need to pass it level by level. As long as the parent component provides certain data, the generation-separated component can directly obtain the data, which is very convenient.

provide data for future generations

Note

In 3.x, provide needed to be imported and enabled in setup, and is now a completely new method.
Every time you want to provide a piece of data, you have to call it separately.
Each time you call it, you need to pass in 2 parameters:

Parameters

Type

Description

key

string

name of data

value

any

data value

// Remember to import provide
import { defineComponent, provide } from 'vue'

export default defineComponent({
  // ...
  setup () {
    // Define the data
    const msg: string = 'Hello World!';

    //provide out
    provide('msg', msg);
  }
})

inject injection

Attention

In 3.x, inject is the same as provide. It needs to be imported first and then enabled in setup. It is also a brand new method.
Every time you want to inject a piece of data, you have to call it separately.
Each time you call it, you only need to pass in 1 parameter:

Parameters

Type

Description

key

string

The data name corresponding to provide

The parameter is the injection name, which is the key

// Remember to import inject
import { defineComponent, inject } from 'vue'

export default defineComponent({
  // ...
  setup () {
    const msg: string = inject('msg') || '';
  }
})

If the provided value is a ref, the ref object will be injected and will notwill be automatically unpacked into its internal value, withresponsive

Example

The subcomponent home uses inject to receive

<template>
  <h3>
{<!-- -->{ homemessage }}
  </h3>
</template>

<script>
import { inject } from 'vue';
export default {
setup(){
    const homemessage=inject("message")
    console.log(homemessage)
    return{
        homemessage
    }
}
}
</script>
<style>
</style>

The parent component app is passed with provide

<template>
  <home></home>
</template>
<script>
import { ref,provide } from 'vue';
import home from "./home.vue"
export default {
    components:{
        home
    },
    setup(){
        const mess = ref("hellomessage")
        provide("message",mess)
        return{
        mess
        }
    }
}
</script>

<style>

</style>

Attention

In general, data passed to descendants should not be changed by descendant components. Descendant components can only obtain data and cannot change data.

setup syntactic sugar

How to use setup script syntactic sugar

You need to enable