A brief analysis of the use of setup() and reactive() functions in vue3
This article will talk to you about the basic concepts of combined API, the concept of setup() entry function, and the use of reactive() in the vue3 project. I hope it will be helpful to everyone!
1. Combined API comparison vue2 project structure
1. Advantages: Easy to learn and use, the location for writing code has been agreed upon.
2. Disadvantages: For large projects, it is not conducive to code reuse, management and maintenance.
3. Explanation: The data and business logic of the same function are scattered in N places in the same file. As the business complexity increases, we need to often use data similar to data() And the back and forth processing in methods
1. Advantages: Data and business logic of the same function can be organized together to facilitate reuse and maintenance.
2. Disadvantages: It requires good code organization and splitting capabilities, and it is not as easy to get started as Vue2.
3. Explanation: Note: In order to allow everyone to transition to the Vue3.0 version better, the writing method of the Vue2.x option API is currently supported.
##2. Use of setup() function
2.1 Basic concept of setup() function
The setup() in Vue3 is a new component configuration item in Vue3, which is used to replace the data() and methods( in Vue2 ), computed() and other configuration items. setup() provides a more concise writing method and can better utilize the Composition API provided by Vue3. The setup() function accepts two parameters, props and context. Among them, props are the property values received by the component, and context contains some configuration information of the component.- 1. What is it: setup is a new component configuration item in Vue3, which serves as the entry function of the combination API.
- 2. Execution timing: Called before instance creation, even earlier than beforeCreate in Vue2.
- 3. Note: Since the instance has not been created when executing setup, the data in data and methods cannot be used directly in setup, so this in Vue3 setup is also is bound to undefined.
return To return, you can use directly in the template (generally, setup cannot be an asynchronous function).
2.2.setup() First experience
App.vue<template> <h1 id="nbsp-msg-nbsp">{{ msg }}</h1> </template> <script> export default { setup() { const msg = 'Hello Vue3' const say = () => { console.log(msg) } return { msg, say } }, } </script>
<script> import { h } from 'vue' export default { name: 'App', setup() { return () => h('h2', 'Hello Vue3') }, } </script>
2.3.reactive() function
Use the reactive function to wrap the array into responsive data. reactive is a function used to wrap ordinary objects/arrays into reactive data for use. It cannot handle basic data types directly (because it is based on Proxy, and Proxy can only proxy objects).For example, when I have a requirement: click to delete the current row informationView through vueTools, the data is deleted after I click it. But there is no actual rendering on the pageApp.vue
<template> <ul> <li v-for="(item, index) in arr" :key="item" @click="removeItem(index)">{{ item }}</li> </ul> </template> <script> export default { name: 'App', setup() { const arr = ['a', 'b', 'c'] const removeItem = (index) => { arr.splice(index, 1) } return { arr, removeItem, } }, } </script>Copy after login
At this time, use reactive() to wrap the array to make it responsive data. Don’t forget to import
<template> <ul> <li v-for="(item, index) in arr" :key="item" @click="removeItem(index)">{{ item }}</li> </ul> </template> <script> import { reactive } from 'vue' export default { name: 'App', setup() { const arr = reactive(['a', 'b', 'c']) const removeItem = (index) => { arr.splice(index, 1) } return { arr, removeItem, } }, } </script>
Now the page is responsive, deleted when clicked, and the page is responsive
<template> <form @submit.prevent="handleSubmit"> <input type="text" v-model="user.id" /> <input type="text" v-model="user.name" /> <input type="submit" /> </form> <ul> <li v-for="(item, index) in state.arr" :key="item.id" @click="removeItem(index)">{{ item.name }}</li> </ul> </template> <script> import { reactive } from 'vue' export default { name: 'App', setup() { const state = reactive({ arr: [ { id: 0, name: 'ifer', }, { id: 1, name: 'elser', }, { id: 2, name: 'xxx', }, ], }) const removeItem = (index) => { // 默认是递归监听的,对象里面任何一个数据的变化都是响应式的 state.arr.splice(index, 1) } const user = reactive({ id: '', name: '', }) const handleSubmit = () => { state.arr.push({ id: user.id, name: user.name, }) user.id = '' user.name = '' } return { state, removeItem, user, handleSubmit, } }, } </script>
Interpretation of the above code:
Do you have a clearer understanding of the use of setup() now? Let’s simplify our writing method below.
2.3.1 Further extraction of reactive()
Optimization: extract the data and business logic of the same function into one function, code Easier to read and easier to reuse.<template> <form @submit.prevent="handleSubmit"> <input type="text" v-model="user.id" /> <input type="text" v-model="user.name" /> <input type="submit" /> </form> <ul> <li v-for="(item, index) in state.arr" :key="item.id" @click="removeItem(index)">{{ item.name }}</li> </ul> </template> <script> import { reactive } from 'vue' function useRemoveItem() { const state = reactive({ arr: [ { id: 0, name: 'ifer', }, { id: 1, name: 'elser', }, { id: 2, name: 'xxx', }, ], }) const removeItem = (index) => { state.arr.splice(index, 1) } return { state, removeItem } } function useAddItem(state) { const user = reactive({ id: '', name: '', }) const handleSubmit = () => { state.arr.push({ id: user.id, name: user.name, }) user.id = '' user.name = '' } return { user, handleSubmit, } } export default { name: 'App', setup() { const { state, removeItem } = useRemoveItem() const { user, handleSubmit } = useAddItem(state) return { state, removeItem, user, handleSubmit, } }, } </script>
将方法抽离出来,用类似于导入的方式进行一个抽离,将数据与方法放在一起,便于我们的统一管理。
2.3.2reactive()再进行进一步文件拆分并且引入
App.vue
<template> <form > <input type="text" v-model="user.id" /> <input type="text" v-model="user.name" /> <button type="submit" @click.prevent="submit">提交</button> </form> <ul> <li v-for="(item, index) in state.arr" :key="item.id" @click="removeItem(index)">{{ item.name }}</li> </ul> </template> <script> import {useRemoveItem,handleSubmit} from './hooks' export default { name: 'App', setup() { const { state, removeItem } = useRemoveItem() const { user, submit } = handleSubmit(state) return { state,removeItem,user,submit } }, } </script>
hooks/index.js
import { reactive } from 'vue' export const useRemoveItem=()=> { const state= reactive( { arr: [ { id: 0, name: 'ifer', }, { id: 1, name: 'elser', }, { id: 2, name: 'xxx', }, ] }) const removeItem=(index)=>{ state.arr.splice(index,1) console.log(state.arr); } return { state, removeItem } } export const handleSubmit=(state)=>{ const user = reactive({ id: '', name: '', }) console.log(1); const submit = () => { state.arr.push({ ...user }) user.id = '' user.name = '' } return { user, submit } }
The above is the detailed content of A brief analysis of the use of setup() and reactive() functions in vue3. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.
