Home > Web Front-end > Vue.js > body text

How to use setup() and reactive() functions in vue3

PHPz
Release: 2023-05-19 16:25:26
forward
1147 people have browsed it

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 back-and-forth processing in methods

##In vue3

  • 1. Advantages: Data of the same function can be Organized together with business logic 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.

How to use setup() and reactive() functions in vue3

2. Use of setup() function

2.1 Setup() function Basic concepts

The setup() in Vue3 is a new component configuration item in Vue3, which is used to replace the data(), methods(), computed() and other configuration items in Vue2. setup() provides a more concise writing method and can better utilize the Composition API provided by Vue3. The setup() function takes two parameters: props and context.. The property values ​​received by the component are stored in props, and some component configuration information is contained in context.

  • 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>
    <h2 @click="say()">{{ msg }}</h2>
</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:

How to use 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;h3&#39;, &#39;Hello Vue3&#39;)
        },
    }
</script>
Copy after login

The console prints Hello Vue3 with the h3 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

How to use 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

How to use 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

How to use 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, making the code more readable and easier to reproduce 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;
    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

Extract the method in a way similar to importing,

Put the data and methods together to facilitate our unified management.

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

How to use 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

The above is the detailed content of How to use setup() and reactive() functions in vue3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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