What is the Composition API of Vue3?

First, let's first understand what the Composition API is. In fact, Composition API is a way to organize Vue code. We know that in traditional Vue, the code of the component is usually composed of a huge,

So, what are the benefits of Composition API? First, it allows us to write cleaner code. You don't need to define a bunch of methods and calculated properties in the component. Instead, you can split these logic into small functions, making the code more readable and understandable. Secondly, the Composition API can help us avoid code duplication. You can extract some common logic and share it among multiple components. In this way, you can avoid duplicating code and improve development efficiency.

Next, let's look at a few examples of using the Composition API.

The first example is a simple computed property. In traditional Vue, we need to return a calculated result in a calculated property. In the Composition API, we can use a simple function to achieve this function.

<template>  
  <div>  
    <p>姓名:{
   
   { fullName }}</p>  
  </div>  
</template>  
  
<script>  
import {
      
       computed } from 'vue';  
  
export default {
      
        
  setup() {
      
        
    const fullName = computed(() => {
      
        
      const firstName = '张三'; // 假设这是从父组件传递下来的数据  
      const lastName = '李四'; // 假设这是从父组件传递下来的数据  
      return `${ 
        firstName} ${ 
        lastName}`;  
    });  
  
    return {
      
        
      fullName,  
    };  
  },  
};  
</script>

In the above example, we defined a computed property fullName using the computed function. This computed property returns a string containing the two variables firstName and lastName passed from the parent component. We then use { { fullName }} in the template to display the result of this computed property. This way, fullName will be updated automatically every time the value of firstName or lastName changes.

The second example is a simple lifecycle hook function. In traditional Vue, we need to define a series of life cycle hook functions in a component. In the Composition API, we can use a simple function to achieve this function.

<template>  
  <div>  
    <p>计数器:{
   
   { count }}</p>  
    <button @click="increment">增加</button>  
  </div>  
</template>  
  
<script>  
import {
      
       onMounted } from 'vue';  
  
export default {
      
        
  setup() {
      
        
    let count = 0; // 假设这是从父组件传递下来的数据  
  
    onMounted(() => {
      
        
      console.log('组件已挂载');  
    });  
  
    const increment = () => {
      
        
      count++;  
    };  
  
    return {
      
        
      count,  
      increment,  
    };  
  },  
};  
</script>

In the above example, we used the onMounted function to define a life cycle hook function. This function will be executed after the component is mounted and output a message in the console. We then use a counter and a button in the template to demonstrate the functionality of this component. When the user clicks the button, the counter value is incremented. In this way, we can avoid using complex calculated properties and lifecycle hook functions in the template.

The third example is an asynchronous operation. In traditional Vue, we need to use async/await or Promise to handle asynchronous operations. In the Composition API, we can use the ref and computed functions to achieve this function.

<template>  
  <div>  
    <p>当前时间:{
   
   { currentTime }}</p>  
    <button @click="fetchCurrentTime">获取当前时间</button>  
  </div>  
</template>  
  
<script>  
import {
      
       ref, computed } from 'vue';  
  
export default {
      
        
  setup() {
      
        
    const currentTimeRef = ref(null);  
  
    const fetchCurrentTime = () => {
      
        
      currentTimeRef.value = fetchCurrentTimeFromServer().then(currentTime => {
      
        
        currentTimeRef.value = currentTime;  
      });  
    };  
  
    const currentTime = computed(() => {
      
        
      return currentTimeRef.value;  
    });  
  
    return {
      
        
      currentTime,  
      fetchCurrentTime,  
    };  
  },  
};  
</script>

In the above example, we use the ref function to define a reference currentTimeRef to store the current time. Then, we defined an asynchronous function fetchCurrentTimeFromServer to get the current time from the server. In the fetchCurrentTime function, we call the fetchCurrentTimeFromServer function and store the result in currentTimeRef. Finally, we use the computed function to define a calculated property currentTime to return the current currentTimeRef value. In this way, every time the value of currentTimeRef changes, currentTime will be automatically updated. When the user clicks the "Get Current Time" button, we will call the fetchCurrentTime function to get the current time and update the value of currentTimeRef. Then, { { currentTime }} in the template will be automatically updated to the latest current time.

Guess you like

Origin blog.csdn.net/2301_77795034/article/details/131234945