Introduction: Using component options (data, computed, Methods, watch) to organize logic in Vue2. X is generally effective. However, when one function of a component becomes complex, the logic code becomes longer and longer (as shown in the figure below). Later maintenance changes to the logic require several changes at the same time, which is not good for maintenance. Therefore, composition API is proposed. Composition API is an API that collects related code of the same logical concern together.

Example of a Vue2. X large component

Vue3. X creates a setup option in the component that is invoked before data Property, computed Property, or methods are resolved, so you cannot use this in setup

Example 1: counter

<template>
<button @click="addCount">
  +
</button>
<div>
  count: {{ state.count }}
</div>
<button @click="delCount">
-
</button>
</template>

<script setup>
import { reactive } from 'vue'

const state = reactive({ 
  count: 9
})

const addCount = () => state.count++
const delCount = () => state.count--
</script>
Copy the code

Example 2: Add, delete, modify and check the list of blogs

<template> <div class="blog"> <div class="blog-add--input"> <textarea v-model="content" rows="5" /> </div> <div Class ="blog-add-- BTN "@click="addBlog"> add </div> <div class="blog-item" v-for="(item, index) in blogs" :key="item.id"> <span class="blog-item--name">{{ item.name }}</span> <span class="blog-item--value">{{ item.value }}</span> <span class="blog-item--time">{{ item.time }}</span> <span class="blog-item--delete" @click="delBlog(index)"> delete </span> </div> </div> </template> <script setup> import {reactive, Vue = reactive([{id: 1, name: 'sera', value: 'reactive ', time: '2021.09.02'}, {id: 2, name:' reactive ') 'taro' value: 'hoe grain to be noon for day, the time:' 2021.09.06 '}, {id: 3, name: 'NGL' value: 'began sweating grain soils' time:' 2021.09.09}, {id: 4, name: 'piluta', value: 'piluta', time: '2021.09.11'}, {id: 5, name: 'jilu', value: 'jilu', time: }]) let content = ref(' ') const delBlog = (index) => {blogs. 1) } const addBlog = () => { blogs.unshift({ id: blogs.length + 1, name: 'ceshi', value: content.value, time: new Date().getTime() }) content.value = '' } </script> <style scoped> .blog { width: 80%; margin: 30px 10%; } .blog-item { border-bottom: 1px solid rgba(0, 0, 0, .15); height: 40px; line-height: 40px; box-sizing: border-box; padding: 0 20px; display: flex; justify-content: space-around; } .blog-add--input textarea{ width: calc(100% - 6px); height: 50px; } .blog-add--btn{ display: flex; justify-content: flex-end; border-bottom: 1px solid rgba(0, 0, 0, .15); height: 40px; line-height: 40px; padding: 0 20px; } </style>Copy the code