Home > Web Front-end > Vue.js > A brief analysis of the use of setup() and reactive() functions in vue3

A brief analysis of the use of setup() and reactive() functions in vue3

青灯夜游
Release: 2023-04-17 18:21:29
forward
2063 people have browsed it

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!

A brief analysis of the use of setup() and reactive() functions in vue3

1. Combined API comparison vue2 project structure

In vue2

  • 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

In vue3

  • 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.

A brief analysis of the use of setup() and reactive() functions in vue3

##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.

Although the data and methods configuration items in Vue2 can also be used in Vue3, it is not recommended. It is recommended that the data and methods are written in the setup function and passed

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 @click="say()">{{ msg }}</h1>
</template>
<script>
    export default {
        setup() {
            const msg = &#39;Hello Vue3&#39;
            const say = () => {
                console.log(msg)
            }
            return { msg, say }
        },
    }
</script>
Copy after login

Effect view:

A brief analysis of the use of setup() and reactive() functions in vue3

Note: Similar to data() and methods in vue2, they need to be written in return before they can be called as results.

[Small interview questions supplement] Must the return in setup be only one object? (setup can also return a rendering function)

App.vue

<script>
    import { h } from &#39;vue&#39;
    export default {
        name: &#39;App&#39;,
        setup() {
            return () => h(&#39;h2&#39;, &#39;Hello Vue3&#39;)
        },
    }
</script>
Copy after login

The console prints Hello Vue3 with the h2 tag.

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 information

App.vue

<template>
    <ul>
        <li v-for="(item, index) in arr" :key="item" @click="removeItem(index)">{{ item }}</li>
    </ul>
</template>

<script>
    export default {
        name: &#39;App&#39;,
        setup() {
            const arr = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]
            const removeItem = (index) => {
                arr.splice(index, 1)
            }
            return {
                arr,
                removeItem,
            }
        },
    }
</script>
Copy after login
View through vueTools, the data is deleted after I click it. But there is no actual rendering on the page

A brief analysis of the use of setup() and reactive() functions in vue3 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 &#39;vue&#39;
    export default {
        name: &#39;App&#39;,
        setup() {
            const arr = reactive([&#39;a&#39;, &#39;b&#39;, &#39;c&#39;])
            const removeItem = (index) => {
                arr.splice(index, 1)
            }
            return {
                arr,
                removeItem,
            }
        },
    }
</script>
Copy after login

A brief analysis of the use of setup() and reactive() functions in vue3 Now the page is responsive, deleted when clicked, and the page is responsive

Similarly: we use reactive() to wrap our objects for use

<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 &#39;vue&#39;
    export default {
        name: &#39;App&#39;,
        setup() {
            const state = reactive({
                arr: [
                    {
                        id: 0,
                        name: &#39;ifer&#39;,
                    },
                    {
                        id: 1,
                        name: &#39;elser&#39;,
                    },
                    {
                        id: 2,
                        name: &#39;xxx&#39;,
                    },
                ],
            })
            const removeItem = (index) => {
                // 默认是递归监听的,对象里面任何一个数据的变化都是响应式的
                state.arr.splice(index, 1)
            }

            const user = reactive({
                id: &#39;&#39;,
                name: &#39;&#39;,
            })
            const handleSubmit = () => {
                state.arr.push({
                    id: user.id,
                    name: user.name,
                })
                user.id = &#39;&#39;
                user.name = &#39;&#39;
            }
            return {
                state,
                removeItem,
                user,
                handleSubmit,
            }
        },
    }
</script>
Copy after login

A brief analysis of the use of setup() and reactive() functions in vue3

Interpretation of the above code:

I defined the input box and the operations of deleting and adding events through v-model Hit the two-way binding data to complete adding and deleting my data.

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 &#39;vue&#39;
    function useRemoveItem() {
        const state = reactive({
            arr: [
                {
                    id: 0,
                    name: &#39;ifer&#39;,
                },
                {
                    id: 1,
                    name: &#39;elser&#39;,
                },
                {
                    id: 2,
                    name: &#39;xxx&#39;,
                },
            ],
        })
        const removeItem = (index) => {
            state.arr.splice(index, 1)
        }
        return { state, removeItem }
    }
    function useAddItem(state) {
        const user = reactive({
            id: &#39;&#39;,
            name: &#39;&#39;,
        })
        const handleSubmit = () => {
            state.arr.push({
                id: user.id,
                name: user.name,
            })
            user.id = &#39;&#39;
            user.name = &#39;&#39;
        }
        return {
            user,
            handleSubmit,
        }
    }
    export default {
        name: &#39;App&#39;,
        setup() {
            const { state, removeItem } = useRemoveItem()
            const { user, handleSubmit } = useAddItem(state)
            return {
                state,
                removeItem,
                user,
                handleSubmit,
            }
        },
    }
</script>
Copy after login

将方法抽离出来,用类似于导入的方式进行一个抽离,将数据与方法放在一起,便于我们的统一管理。

2.3.2reactive()再进行进一步文件拆分并且引入

A brief analysis of the use of setup() and reactive() functions in vue3

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 &#39;./hooks&#39;
  export default {
      name: &#39;App&#39;,
      setup() {
          const { state, removeItem } = useRemoveItem()
          const { user, submit } = handleSubmit(state)
          return {
              state,removeItem,user,submit
          }
      },
  }
</script>
Copy after login

hooks/index.js

import { reactive } from &#39;vue&#39;
export const useRemoveItem=()=> {
  const state= reactive( {
          arr: [
                    {
                        id: 0,
                        name: &#39;ifer&#39;,
                    },
                    {
                        id: 1,
                        name: &#39;elser&#39;,
                    },
                    {
                        id: 2,
                        name: &#39;xxx&#39;,
                    },
                ]
              })
  const removeItem=(index)=>{
      state.arr.splice(index,1)
            console.log(state.arr);
          }
      return { state, removeItem }
}
export const handleSubmit=(state)=>{
  const user = reactive({
                id: &#39;&#39;,
                name: &#39;&#39;,
            })
            console.log(1);
  const submit = () => {
       state.arr.push({
        ...user
       })
       user.id = &#39;&#39;
       user.name = &#39;&#39;
            }
      return { user, submit }
}
Copy after login

(学习视频分享:vuejs入门教程编程基础视频

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template