This article will talk about two different writing styles of vue components, and introduce the optional API and combined API in detail. I hope it will be helpful to everyone!
With the gradual stabilization of vue3 and the improvement of the surrounding ecology, vue3 has now become the default usage
So, for a front-end development First, you need to know both Vue2 and Vue3. Many new things are added in vue3, such as: Fragment, Teleport, Suspense, and some features in vue2 are also removed, such as: removing keyCode support as a modifier of v-on, etc.
There are also some differences in programming style
Optional API can also become a configuration item API, which is an instance option object of a component To describe the logic of the component, such as: the component'sdata
,methods
, as well as the life cycle hookmounted
, and thewatch
listener. [Related recommendations:vuejs video tutorial,web front-end development] The properties defined by
components will be exposed onthis
inside the function, It will point to the instance of the current component. Within the life cycle and methods, it can be accessed and read throughthis
The following option formulaAPI
The sample code is as follows
选项式API累加 {{count}}
For the optionalAPI
, it is thevue2.0
writing specification. The responsive data related to the page display is mounted indata
Next, the binding method is placed inmethods
. It is a conventional
some option configuration parameters and a configurable
combinationAPI
(Composition API
) is a collection ofAPI
passed CombinedAPI
can be imported fromvue
by importing specificAPI
(such asref
(common data type),reactive
(only applicable to objects)), functions describe the logic of components and achieve the functions we want
Usually, the combination will be combined withUse with
Thissetup
is an identifier, just liketype="text/javascript"
, tellingvue
what needs to be done Some processing during compilation
allows us to use the combinedAPI
concisely, such as: import and top-level inVariables or functions can be written directly using
in the template instead of declaring options to writevue
components. CombinedAPI
is just a general technical term. Because it combines someAPI
[1].Responsive API: For example:ref()
andreactive()
, you can directly create basic data type reactive and object data type reactive
[2].Life cycle hook: For exampleonMounted()
,onUnmounted()
, you can add logic in the life cycle stage of the component
[3].Dependency injection: useprovide()
Withinject()
, you can use the dependency injection system ofVue
when using the responsiveAPI
The specific code is as follows
组合式API累加 {{count}}
[1]. You need to introduce the ref API function[2] from
. In the logic code of the component, you need to usexxx.value
Get the value and modify
[3]. There is no need to writexxx.value
in the template. The responsive variable data defined in the function can be used directly in the template
It can be seen from the comparison between the optionalAPI
and the combinedAPI
two code writing styles that if the optionalAPI
is used, then the page The bound responsive data needs to be mounted under thedata
configuration option, while the binding method
needs to be placed under themethods
configuration option. The writing methods are fixed. Yes, in the option typeAPI
, if you want to access properties and methods within the logic, you rely more onthis
to access the data and methods under the component instance, while in the combined type API refers to what is specifically needed, and the API that solves the problem and function is introduced fromvue
to truly introduce it on demand
If you want a basic data with responsive capabilities, then It needs to be wrapped with the ref function. At this time, it has the ability to be responsive.
However, in the component code, there is nothis
binding.this
will isundefined
, you can access the value exposed by the combinedAPI
in the optionalAPI
, but not the other way around
As shown below The picture is a good comparison of the difference between optionalAPI
and componentAPI
vue2
has been stable for many years, and the surrounding ecology has been very complete. Options API and component API, two different styles of code, neither one is good or bad
Only you are familiar with or not,Vue3
is an upgrade and expansion ofvue2
provides two different sets of The interface is for developers to freely choose and use
OptionalAPI
is centered on the component instance, with the constructor function, that is,this
as the core. For those who are familiar with object-oriented For language developers, the use of classes becomes more harmonious
It abstracts the details related to components, such as data and methods, and uses some agreed rules to combine the data and methods. Separate, keep each independent, and organize our code in an optional manner
It is very friendly to novices
The core of the combined API is to define the response directly within the function scope Unlike the option API, it does not need to be mounted to thedata
instance option.
It obtains the state directly from the function, by directly accessing thevue
Introducing corresponding responsive API functions to package cardinal data types and non-basic data types
Realizing data responsiveness
This programming method is more free and the code execution efficiency is higher It will also be higher, and its flexibility makes the pattern of organizing and reusing logic very powerful
Ifvue2
is a wild horse with a tightrope, thenvue3
It means breaking away from the tight horse and becoming freer
[1].Vue2
andVue3
It can also be mixed, but you can just choose a coding method that you like and are familiar with. It is nothing more than one more style of coding
[2]. In a production project, when you do not need to use a build tool , or you plan to usevue
in low-complexity scenarios, such as progressive enhancement application scenarios, then the official recommendation is that you use the optionalAPI
, which isvue2
's programming style
[3]. When you plan to usevue
to build a complete single-page application, then the official recommendation is to use the combinedAPI
single file component method Go build your own project
invue3
andvue2.7
For versions above, you can use the combinedAPI
. For lower versionsvue2.7
and below, you can use the officially maintained plug-in @vue/composition-api
Invue3
, the combinedAPI
will basically be used in single file components withsyntax
The style of composed API is based on the combination of functions, but it is not functional programming
Function Formula programming: Functions can be passed as data and parameters. Functions are the first citizens, pure UI functions. If you have used React, you will know this
Pure function: A stateless world with input and output, high-order functions in React, and map and reduce in arrays are all functional programming
combinationAPI
is It is based on the variable data and fine-grained responsive system inVue
, while functional programming usually emphasizes the immutability of data, which is one-way data flow
CombinedAPI
can pass combined functions To achieve more concise and efficient logic reuse, in the optionalAPI
our main logic reuse mechanism ismixins
, and with the combinedAPI
, Can solve all the defects inmixins
option-based API invue2.0
In programming, you must follow the usage specifications ofvue
to organize your own code. Reactive data is placed underdata
, while methods are placed under methods
However, when the logic of a single file component in the optional API is complex to a certain extent, some problems will arise. These problems are mainly related to multiple logical concerns.
You have to scroll up and down in the file component to view Code snippets
Code that handles the same logical concerns is forced to be split in different options, located in different parts of the file
In a large component such as hundreds of lines, it is necessary to To understand a logical concern in the code, you need to scroll up and down the current file. If you want to extract and reconstruct a logical concern
into a reusable tool function, you need to start from Multiple different parts of the file to find the correct fragment needed, and if this component is refactored using the composition API
The organization of the code logic will become very clear
Now with the same The code related to a logical concern is grouped into one group. We no longer need to scroll back and forth between different option blocks for a logical concern
In addition, this group of code can also be moved to an external In the file, there is no need to reorganize the code for abstraction, which greatly reduces the cost of reconstruction
This is very important in some large projects and is conducive to the maintenance and iteration of the project
CombinedAPI
Mainly utilize basic variables and functions, which are themselves type-friendly, and are rewritten with the composed API The code can enjoy complete type derivation without writing too many type annotations
Most of the time, the combinedAPI
code written inTs
andjs
The writing is similar
Using combinedAPI
is more efficient than optional API , because the combined API does not automatically introduce the life cycle, it is a pure function, and is more friendly to code compression
This is also written in the form ofThe component template is compiled into an inline function, and the code in
is in the same scope
Unlike the option-styleAPI
Need to rely onthis
context object to access properties. The compiled template can directly access the variables defined inwithout the need for optional API , The agent
in the instance object uses the combinedAPI
, which is more friendly to code compression, because the names of local variables can be compressed, but the attribute names of the object cannot
Using combined API is not like option-based API, which will conventionally mount the specified logic under the specified option configuration object. Its programming The use of styles is fixed, and it is indeed possible to write Vue components
so that developers have less to think about. You only need to follow the recipe and do it step by step in sequence
And the combined style API, which is more biased towards native js, is not subject to the rules and restrictions of the framework. It is relatively free and easy. You can write component code just like ordinary javascript.
You can write organizedjavascript
, Ability to write combined API code
Optional API code style can indeed reduce your thinking time to a certain extent. If you want to implement a specific function, then you need to organize yourself according to the rules of the framework Code, there is no room for choice
This will also cause a problem. If it is out of the framework, then it will not work
In some relatively large-scale projects, optional API code It is very laborious to refactor the style, and it is difficult to refactor and improve the code quality. In this regard, the combined API provides better long-term maintainability
In the official introduction, the combined API can basically cover all state logic needs, that is to say, the functions implemented using the vue2 optional API
The same use ofvue3
can still be achieved
OptionalAPI
and combinedAPI
can be mixed. If you want to use the combinedAPI
in the optionalAPI
, it is based onVue3
orvue2 Versions after .7
can use the combined API through thesetup()
option
In the official documentation, it is mentioned that in an option-basedAPI
In projects that have been developed for a long time but need to be integrated with new code or third-party libraries based on the combined API, usesetup()
In other words,vue2
projects still use the optional API method, while Vue3 projects use the combined API, which is nothing more than an additional style of writing code
options The optional API will not be abandoned and is an integral part of vue. The optional API is implemented on the basis of the combined API. For small and medium-sized projects, using the optional API is a good choice
And combined The API is more suitable for large and complex projects. Both coding styles can be implemented. It depends on which one you are more familiar with and prefer.
OptionAPI
and combinedAPI
are two different programming styles provided byVue
. Before thevue2.7
version, option style was usedAPI
, responsive data needs to be mounted under data, and methods need to be mounted undermethods
. In the combined API, you only need to add ## in the script tag. After #setupis marked, it means that it has a combined
APIusage environment. If
API fromvue
Function, variables and functions defined in
scriptcan be used directly in the template. It is more of a style change that allows the front end to better organize the logic code
vuejs introductory tutorial,Basic programming video)
The above is the detailed content of Let's talk in depth about the two different writing styles of Vue components.. For more information, please follow other related articles on the PHP Chinese website!