Composition API background:
When we components become larger, the business logic of concerns code also can become long, if want to find a code in many place has the property of the frequent operation of new demand specific operation, will be in 100 or more lines of code hopping, found belongs to the logic of this attribute, especially when the new personality on project, which can result in component is difficult to read and understand.
The ability to configure code related to the same logical problem in the CompositionAPI is exactly what we need.
Use of the setup function:
1.Com Position API all code before writing, must be built on the setup function;
Setup (props, context){} is executed before the Created instance is fully initialized;
3. Since setup is executed before the instance is initialized, there is nothing on this in setup;
4. Do not use this in setup.
External methods (template/mounted... The methods /...) ; Setup (){} must return{}, whose return contents are exposed externally. So you can use the variables and functions that return from template directly... ;Copy the code
const app = Vue.createApp({ methods: { test() { console.log(this.$options.setup()); } }, template: ` <div @click="handleClick">{{name}}</div> `, mounted() { this.test(); }, setup(props, context) { return { name: "zhz", handleClick: () => { alert("setup"); }}}}); const vm = app.mount("#root");Copy the code
How to organize code in THE Options API VUe2: We define attributes and methods in a vUE file called Data, Methods, computed, and Watch to deal with page logic shortcomings: A function often needs to define attributes and methods in different VUE configuration items, which is relatively scattered, small project is good, clear, but when the project is large, a method may contain many methods, often it is not clear which method corresponds to which function advantage: beginners will be easier to get started
In Vue3 Composition API, code is organized according to logical functions. All apis of a function are put together (high cohesion, low coupling). In this way, even if the project is large and has many functions, we can quickly locate all apis used by the function. Unlike the vue2 Options API, the apis used for a function are scattered and need to be changed. The process of searching for THE API is time-consuming. The learning cost may increase, and the previous way of thinking also needs to be changed. Composition API organizes code according to logical dependencies to improve readability and maintainability. API based on function Composition makes it easier to reuse logical code (reuse logical code through Mixins in VUe2 Options API is prone to naming conflicts and unclear relationships).