This article has more dry goods. It is recommended to collect!
When upgrading from vue2 to vue3, vue3 is compatible with vue2, so vue3 can adopt the optional API of vue2. Because one variable of the optional API exists in many places, if there is a problem, you need to check in multiple functions. When the project is large, it will encounter problems and increase the difficulty of troubleshooting. Therefore, the setup configuration item is added in vue3 to write the composite API.
1, Difference between optional API and composite API
Some students have been using vue it for a year without knowing the optional api! Are you that classmate? If so, put it away.
The Options API in vue2 is an optional api, either in Chinese or English.
In a vue file, data, methods, mounted, computed, watch, etc. are used to define properties and methods to jointly process page logic. We call this method Options API.
Example 1: counter
<template> <div> <button @click="add">+</button> {{num}} <button @click="reduce">-</button> </div> </template> <script> export default { data(){ return { num:0 } }, methods:{ add(){ this.num++ }, reduce(){ this.num-- } } } </script>
Observing the above examples, we find that the processing of num value involves two options: data and methods. The business processing is relatively scattered, and it looks clear when the project is small. However, after the project becomes larger, data and methods will contain many attributes and methods. At this time, it is difficult to distinguish which attribute corresponds to which method. So vue3 add setup to write composite API.
Vue3's Composition API is a composite api.
The composite api is a function defined api that will be put together, so that even if the sub project becomes larger and the function increases, we can quickly find all APIs related to the function. Unlike the Options API, the functions are scattered, and it is difficult to find multiple places when changes are needed.
Example 2: counter
<template> <div> <button @click="add">+</button> {{num}} <button @click="reduce">-</button> </div> </template> <script> import { ref } from 'vue' export default{ setup(){ const num = ref(1) return{ num, add(){ num.value++ }, reduce(){ num.value-- } } } } </script>
ref makes the basic data type responsive. The next article introduces its usage in detail. Students who need it can pay attention to it and don't get lost!
Use a picture to tell you the difference between them:
2, How to use setup?
2.1 When will setup be executed?
setup is used to write composite APIs. From the perspective of life cycle hook functions, it is equivalent to replacing beforeCreate. Will be executed before creted.
<script> export default{ created(){ console.log('created'); }, setup(){ console.log('setup'); } } </script>
After execution, the setup print result is always in front.
2.2 how to use setup data and methods?
Example 3: directly defining usage variables
<template> {{a}} </template> <script> export default{ setup(){ const a = 0 } } </script>
Abnormal results found after running:
runtime-core.esm-bundler.js?5c40:6584 [Vue warn]: Property "a" was accessed during render but is not defined on instance.
The property a we are prompted to access is not mounted on the instance.
The attributes and methods inside setup must be exposed. Mount the attributes on the instance. Otherwise, there is no way to use them. Add the above code return:
<script> export default{ setup(){ const a = 0 return{ a } } } </script>
2.3 is there this in setup?
Print this in the setup, and the returned result is undefined. This indicates that this does not exist in setup, and things related to this cannot be mounted.
2.4 how to use the hook function in setup?
vue3 is an optional writing method compatible with vue2, so the hook function can exist side by side with setup, which is equivalent to the Options API.
Example 4:
export default{ setup(){ console.log('setup'); }, mounted(){ console.log('mounted'); } }
The setup() function added in vue3 is used to write composite APIs, so it is not recommended to write code like this. So we need to register the hook function with the function of the onXXX family. After the registration is successful, we call a callback function.
Example 5:
import { onMounted } from "vue"; export default{ setup(){ const a = 0 return{ a }, onMounted(()=>{ console.log("implement"); }) } }
These registered life cycle hook functions can only be used synchronously during setup, because they rely on the global internal state to locate the current component instance, and will throw an error when calling a function not under the current component.
Other hook functions are the same. Just introduce them as needed.
2.5 relationship between setup and hook function
When setup is juxtaposed with hook functions, setup cannot call lifecycle related functions, but lifecycle can call setup related properties and methods.
Example 6:
<template> <button @click="log">Point me</button> </template> <script> export default{ setup(){ const a = 0 return{ a } }, methods:{ log(){ console.log( this.$options.setup() );//Returns an object } } } </script>
this.$options.setup() returns a large object that contains all the properties and methods in setup.
3, setup parameters
When using setup, it will receive two parameters: props and context.
3.1,props
The first parameter is props, which means that the parent component passes values to the child component. Props is responsive and will be updated automatically when a new props is passed in.
Example 7:
export default{ props: { msg: String, ans: String, }, setup(props,context){ console.log(props);//Proxy {msg: "anxious to find someone", ans: "do you have someone?"} }, }
Because props is responsive, it cannot be deconstructed with ES6, which will eliminate the response characteristics of props. At this time, it is necessary to borrow toRefs for deconstruction. Example 8:
import { toRefs } from "vue"; export default{ props: { msg: String, ans: String, }, setup(props,context){ console.log(props); const { msg,ans } = toRefs(props) console.log(msg.value); //Anxious to find someone console.log(ans.value); //Are you single? }, }
When using components, we often encounter optional parameters. Some places need to pass a value, and some times do not. How to deal with it?
If ans is an optional parameter, there may be no ANS in the incoming props. In this case, toRefs will not create a ref for ans, and you need to use toRef instead.
import { toRef } from "vue"; setup(props,context){ let ans = toRef(props ,'ans')// Create an ans when it does not exist console.log(ans.value); }
3.2,context
Context context environment, which includes three parts: attribute, slot and custom event.
setup(props,context){ const { attrs,slots,emit } = context // attrs gets the attribute value passed by the component, // Slots in slots component // emit custom event subcomponent }
attrs is a non responsive object, which mainly receives the no props attribute and is often used to pass some style attributes.
Slots is a proxy object, where slots.default() obtains an array. The length of the array is determined by the slot of the component, and the slot content is in the array.
This does not exist in setup, so emit is used to replace the previous this.$emit. When the child passes to the parent, the user-defined event is triggered.
Example 9:
<template> <div :style="attrs.style"> <slot></slot> <slot name="hh"></slot> <button @click="emit('getVal','Transfer value')">Pass value from child to parent</button> </div> </template> <script> import { toRefs,toRef } from "vue"; export default{ setup(props,context){ const { attrs,slots,emit } = context // attrs gets the style attribute passed by the component console.log('slots',slots.default());//Slot array console.log('Slot properties',slots.default()[1].props); //Gets the properties of the slot return{ attrs, emit } }, } </script>
4, Summary of setup features
1. This function will be executed before created, as explained above.
2. There is no this in setup. You can't mount things related to this.
3. The attributes and methods inside setup must be return ed, otherwise there is no way to use them.
4. setup internal data is not responsive.
5. Setup cannot call lifecycle related functions, but lifecycle functions can call functions in setup.