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

Learn more about the most commonly used JavaScript events

Table of contents JavaScript events: Commonly use...

jQuery canvas generates a poster with a QR code

This article shares the specific code for using j...

Summary of examples of common methods of JavaScript arrays

Table of contents Common array methods concat() M...

In-depth understanding of the vertical-align property and baseline issues in CSS

vertical-align attribute is mainly used to change...

Completely uninstall MySQL database in Windows system to reinstall MySQL

1. In the control panel, uninstall all components...

The latest collection of 18 green style web design works

Toy Story 3 Online Marketing Website Zen Mobile I...

Vue implements bottom query function

This article example shares the specific code of ...

Detailed explanation of Nginx http resource request limit (three methods)

Prerequisite: nginx needs to have the ngx_http_li...

Learn MySQL in a simple way

Preface The database has always been my weak poin...

Linux 6 steps to change the default remote port number of ssh

The default ssh remote port in Linux is 22. Somet...

MySQL 5.7.19 installation and configuration method graphic tutorial (win10)

Detailed tutorial on downloading and installing M...

HTML form tag tutorial (2):

This tutorial introduces the application of vario...

Example code for configuring monitoring items and aggregated graphics in Zabbix

1. Install Zabbix Agent to monitor the local mach...

Introduction to HTML_PowerNode Java Academy

What is HTML? HTML is a language used to describe...