Introduction to Vue3 Composition API

Introduction to Vue3 Composition API

Vue3.0 released the rc version in July. After vue-cli4.5, it also supports selecting vue3 as an alternative version for experience. The official version of vue3 is probably not far away. I can’t learn anymore!!!!
Compared with vue2.0 version (Option API), Composition API is one of the major changes in 3.0.

Overview

The Composition API is mainly inspired by React Hooks. Its purpose is to enable us to more flexibly "combine" the logic of components through a set of low-intrusive, functional APIs.

Example

<template>
 <div>{{count}}</div>
 <button @click="addCount">Add</button>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';

export default defineComponent({
 name: 'App',
 setup () {
  const count = ref(0)
  const getCount = () => {
   count.value = Math.floor(Math.random() * 10)
  }
  const addCount = () => {
   count.value++
  }
  onMounted(() => {
   getCount()
  })

  return {
   count,
   addCount
  }
 }
});
</script>

As the name suggests, the Composition API no longer passes in parameters such as data and mounted. Instead, it implements two-way binding of data and execution of lifecycle functions through the introduction of methods such as ref and onMounted.

Why is it needed?

1. When the component is complex, the logic code can be combined together without being forcibly separated by options. This raises the upper limit of code quality while also lowering the lower limit of code quality. A comparison chart from the official website:

2. Better reuse.

In vue2, if you want to reuse some logic code, you can add it through mixin. But the content of the mixin is actually not intuitive, and the same name will be overwritten. With the composition API, since all methods are imported, a single logic can be encapsulated. For example, encapsulate the countdown function for sending verification codes.

<template>
 <input type="number" placeholder="Please enter the verification code">
 <button v-if="count">Can be resent after {{count}} seconds</button>
 <button v-else @click="startCount">Send verification code</button>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';

const userCountDown = () => {
 const count = ref(0)
 const countDown = (num: number) => {
  count.value = num
  num--
  if (num > 0) {
   setTimeout(() => {
    countDown(num)
   }, 1000)
  }
 }
 const startCount = () => {
  // get verifyCode
  countDown(60)
 }

 return { count, startCount }
}

export default defineComponent({
 name: 'Home',
 setup () {
  const { count, startCount } = userCountDown()
  return { count, startCount }
 }
});
</script>

3. Better TypeScript support. We won't add a lot of content to the vue prototype, but by introducing it, the type definition will be clearer.

setup

Setup is a new option added by Vue, which is the entry point for using Composition API in components. Setup is executed after creating the Vue component instance and completing the initialization of props. Because setup is called before option api is parsed, the this in setup will be completely different from that in options. To avoid confusion, do not use this in setup. At the same time, the value returned by setup can be used in templates and other options. From a design perspective, Vue officially completes everything in setup. The return value of setup connects the template template and method.

ref、reactive

Since data is no longer passed in, creating and listening to data in a responsive manner requires the ref or reactive functions exposed by Vue. There is a difference between the two. ref is used for data of basic assignment type, while reactive is used for data of reference type.

The value of the basic assignment type needs to be obtained and modified using the .value method in the setup method. Because if the value of the assignment type is returned, the double binding of the data is lost. But in template, direct access is possible.

<template>
 <div>{{count}}
  <button @click="changeCount">Add</button>
 </div>
 <div>The student's name is: {{student.name}}</div>
 <div>The student's age is: {{student.age}}
  <button @click="changeStudentAge(20)">Add</button>
 </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';

export default defineComponent({
 name: 'Home',
 setup () {
  const count = ref(0)
  const changeCount = () => {
   count.value = count.value + 1
  }
  const student = reactive({
   name: 'Bob',
   age: 12
  })
  const changeStudentAge = (age: number) => {
   student.age = age
  }
  return {
   count,
   changeCount,
   student,
   changeStudentAge
  }
 }
});
</script>

computed and watch

<template>
 <div>{{count}}</div>
 <div>{{doubleCount}}</div>
 <button @click="addCount">Add</button>
</template>

<script lang="ts">
import { defineComponent, ref, computed, watchEffect, watch } from 'vue';

export default defineComponent({
 name: 'App',
 setup () {
  const count = ref(0)
  watch(count, () => { // If multiple, pass in [count, count1] as an array
   console.log('watch', count.value)
  })
  watchEffect(() => {
   console.log('watchEffect', count.value)
  })
  const addCount = () => {
   count.value++
  }
  const doubleCount = computed(() => {
   return count.value * 2
  })
  return {
   count,
   doubleCount,
   addCount
  }
 }
});
</script>

The difference between watch and watchEffect is that watchEffect will be executed immediately, and the responsive data read during the execution will be observed. And watch will only be executed when the watch object changes.

life cycle

  • beforeCreate -> Using setup()
  • created -> use setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

The above is the detailed content of the introduction to the use of Vue3 Composition API. For more information about the use of Vue3 Composition API, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of one way to use the Composition API of vue3.0
  • Example of using Composition API of Vue3.0
  • New features of Vue3: Using CSS Modules in Composition API
  • A brief introduction to the composition-api of the new version of Vue3.0 API
  • Detailed explanation of extraction and reuse logic in Vue3 Composition API
  • A brief discussion on how Vue3 Composition API replaces Vue Mixins
  • How to implement logic reuse with Vue3 composition API

<<:  Detailed explanation of the four transaction isolation levels in MySQL

>>:  How to install lua-nginx-module module in Nginx

Recommend

Examples of implementing progress bars and order progress bars using CSS

The preparation for the final exams in the past h...

JavaScript data flattening detailed explanation

Table of contents What is Flattening recursion to...

A brief analysis of HTML space code

How much do you know about HTML? If you are learni...

MySQL spatial data storage and functions

Table of contents 1. Data Type 1. What is MySQL s...

Detailed explanation of the difference between in and exists in MySQL

1. Prepare in Advance For your convenience, I cre...

Three ways to achieve text flashing effect in CSS3 Example code

1. Change the transparency to achieve the gradual...

mysql method to view the currently used configuration file my.cnf (recommended)

my.cnf is the configuration file loaded when MySQ...

Build a Docker private warehouse (self-signed method)

In order to centrally manage the images we create...

Detailed explanation of MySQL transactions and MySQL logs

Transactional Characteristics 1. Atomicity: After...

Basic syntax of MySQL index

An index is a sorted data structure! The fields t...