Vue3 inherits all the lifecycle functions of Vue2, so the lifecycle application of Vue2 is also applicable to Vue3. Vue3 also has some new life cycles.

We don’t want to talk too much about the original life cycle functions. Let’s explain what life cycle functions Vue3 has changed and added compared with Vue2

  • beforeUnmount unmounted

These two lifecyms replace Vue2’s beforeDestory and DeStoryed lifecyms. They both have the same function and are called when a component is uninstalled. In Vue3 you can also uninstall the application using the Unmout API

  • renderTracked

    It is called when tracking the virtual DOM rendering and when receiving debugger events as parameters for the component’s first rendering. It is not called when data changes

      <p>Cart: {{cart}}</p>
      <script>
        export default {
          data() {
            return {
              cart: 1}},// key: the key name of the rendered property
          // target: the render property's key-value pair
          // type: the operation on the current attribute
          renderTracked({key, target, type}){}}</script>
    Copy the code
  • renderTriggered

    When the virtual DOM is rerendered to triggered.Similarly to renderTracked, receives a Debugger event as an argument. This event tells you what action triggers rerendering and when the target object and key of the action trigger a change in the property value

      <p>Cart: {{cart}}</p>
      <script>
        export default {
          data() {
            return {
              cart: 1}},// key: the key name of the rendered property
          // target: the key pair of the render property. The value is the modified value
          // type: the operation on the current attribute
          renderTracked({key, target, type}){}mounted() {
            setTimeout(() = > {this.cart++}, 10000)}}</script>
    Copy the code
  // Create an application
  const app = createApp({})
  app.mount("#app")

  // Uninstall the application
  app.unmount("#app")
Copy the code
  • setup -> createdbeforeCreate

Setup is executed before the component is created, as an entry point to the composite API, and the return value of the return can be rendered to the page

The ginseng

  1. The props object passed in by the props parent is responsive, and is updated when a prop changes

Note that you can’t use structural assignment, otherwise you lose the responsiveness if you want to deconstruct itpropsYou can optionally use the properties intoRefsTo do this

<setup-hook :time="time" other="other" :other-time="time" @success="handleSuccess">
  <span> 23123</span>
  <template v-slot:title> 23123</template>
  <template v-slot:bottom> 23123</template>
</setup-hook>
<script>
  export default {
    data() {
      return {
        time: 1000}},mounted() {
      setTimeout(() = > {
        this.time += 1000
      }, 1000)},methods: {
      handleSuccess() {
        console.log('success')}}}</script>
Copy the code
~~~ HTML <div> <div> {{time}} < / div > < div > interception props {{newTime}} < / div > < div > toRefs (props) {{refTime}} < / div > < / div > < script lang = "ts" > import {toRefs} from 'vue' export default { setup(props) { let {time: newTime} = props let {time: refTime} = toRefs(props) console.log(refTime) return { newTime, refTime } } } </script> ~~~Copy the code

When using toRefs to deconstruct props, you need to access its value property to access it directly. The following is the printed deconstructed value. Finally, you need to use return to throw variables and methods that need to be rendered and used

  1. contextExposed three componentsproperty (attrs.slots.emit)

Attrs attribute passed by the parent component on the child component (not received by props)

Slots a slot passed into a child component has a default slot by default

Emit This is an execution function, equivalent to vue.$emit(), which can be used to send events

Context is a normal JavaScript non-responsive object that can safely use ES6’s destruct assignment operations

~~~html <! <span> 23123</span> <span> </span> <template v-slot:title> 23123</template> <template v-slot:bottom> 23123</template> </setup-hook> <! --> <script> setup(props, {attrs, emit, slots}) {let {time: newTime} = props let {time: refTime} = toRefs(props) console.log(refTime) console.log(attrs, slots) emit('success') return { newTime, refTime } }, </script> ~~~Copy the code

Therefore, when setup is executed, the component instance is not created and can only access props, attrs, slots, and EMIT instances, but not data, computed, and Methods

Setup has a return value at the end, which is an object containing variables that we need to render or use in other life cycles.

Here are a few things to note when using setup:

  1. This in setup is not a reference to a Vue instance, because setup() is called before the other component options are parsed, so this inside setup() behaves completely differently than this in the other options. This can cause confusion when using setup() with other optional apis.

  2. In setup, if we define a variable that refers to a type, and we delay the change to that variable, the value will not change the page rendering because we are not defining reactive data. If we want to create reactive data, we can use Reactive to create it

  let obj = reactive({value: 1.label: 'object'})
Copy the code
  1. This can be used if we define a variable of an underlying type and want it to implement a variation of the reactive typerefTo create, access the value of the object can be accessed by accessing the variable’svalueattribute
  const count = ref(0)
  console.log(count.value) / / 0
  // It is also possible to type within a ref
  const count = ref<string | number>(0)
Copy the code
  1. setupThe return value of can be passed directly in other life cycles or functionsthisCall, and has been processed responsively

Also added to Setup are several lifecycle hook functions that can only be used in Setup

onBeforeMount onMounted onBeforeUpdate onUpdated onBeforeUnmount onUnmount onErrorCaptured onRenderTracked onRenderTriggered

The details are similar to life cycle functions, but note that these can only be used in setup

  setup() {
    onMounted(() = > {
      console.log('mounted')})}Copy the code

Vue3 also provides provide and Inject for provisioning and injection in setup

  setup() {
    provide('title'.'this is a title')}setup() {
    const title = inject('title'.'default value')}Copy the code