Home >Web Front-end >Vue.js >Let's talk in depth about the two different writing styles of Vue components.
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's data
, methods
, as well as the life cycle hook mounted
, and the watch
listener. [Related recommendations: vuejs video tutorial, web front-end development] The properties defined by
components will be exposed on this
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 through this
The following option formulaAPI
The sample code is as follows
<template> <div class="base-vue3-code-style"> <el-button type="danger" @click="handleIncrease" >选项式API累加</el-button> <p>{{count}}</p> </div> </template> <script> export default { data() { return { count:0 } }, methods: { // 定义方法,修改data下面的数据 handleIncrease() { this.count++ } }, }; </script> <style scoped> .base-vue3-code-style { text-align: center; } </style>
For the optional API
, it is the vue2.0
writing specification. The responsive data related to the page display is mounted in data
Next, the binding method is placed in methods
. It is a conventional
some option configuration parameters and a configurable
combinationAPI
(Composition API
) is a collection of API
passed Combined API
can be imported from vue
by importing specific API
(such as ref
(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 with 5101c0cdbdc49998c642c71f6b6410a82cacc6d41bbb37262a98f745aa00fbf0
Use with
This setup
is an identifier, just like type="text/javascript"
, telling vue
what needs to be done Some processing during compilation
allows us to use the combined API
concisely, such as: import and top-level in 5101c0cdbdc49998c642c71f6b6410a82cacc6d41bbb37262a98f745aa00fbf0
Variables or functions can be written directly using
in the template instead of declaring options to write vue
components. Combined API
is just a general technical term. Because it combines some API
[1]. Responsive API: For example: ref()
and reactive()
, 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: use provide()
With inject()
, you can use the dependency injection system of Vue
when using the responsive API
The specific code is as follows
<template> <div class="base-vue3-code-style"> <el-button type="primary" @click="handleIncrease" >组合式API累加</el-button> <p>{{count}}</p> </div> </template> <script setup> // 引入ref API import {ref} from "vue"; // 响应式数据状态,初始化数据,ref接受一个内部值,返回一个响应式的、可更改的 ref 对象,此对象只有一个指向其内部值的属性 const count = ref(0); // 用来修改状态,触发更新元素,注意的是需要在逻辑中,需要使用`.value`进行访问 function handleIncrease() { count.value++; } </script>
[1]. You need to introduce the ref API function [2] from
. In the logic code of the component, you need to use xxx.value
Get the value and modify
[3]. There is no need to write xxx.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 optional API
and the combined API
two code writing styles that if the optional API
is used, then the page The bound responsive data needs to be mounted under the data
configuration option, while the binding method
needs to be placed under the methods
configuration option. The writing methods are fixed. Yes, in the option type API
, if you want to access properties and methods within the logic, you rely more on this
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 from vue
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 no this
binding. this
will is undefined
, you can access the value exposed by the combined API
in the optional API
, but not the other way around
As shown below The picture is a good comparison of the difference between optional API
and component API
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 of vue2
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 the data
instance option.
It obtains the state directly from the function, by directly accessing the vue
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
If vue2
is a wild horse with a tightrope, then vue3
It means breaking away from the tight horse and becoming freer
[1]. Vue2
and Vue3
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 use vue
in low-complexity scenarios, such as progressive enhancement application scenarios, then the official recommendation is that you use the optional API
, which is vue2
's programming style
[3]. When you plan to use vue
to build a complete single-page application, then the official recommendation is to use the combined API
single file component method Go build your own project
in vue3
and vue2.7
For versions above, you can use the combined API
. For lower versions vue2.7
and below, you can use the officially maintained plug-in @vue/composition-api
In vue3
, the combined API
will basically be used in single file components with 5101c0cdbdc49998c642c71f6b6410a82cacc6d41bbb37262a98f745aa00fbf0
syntax
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 in Vue
, 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 optional API
our main logic reuse mechanism is mixins
, and with the combined API
, Can solve all the defects in mixins
option-based API in vue2.0
In programming, you must follow the usage specifications of vue
to organize your own code. Reactive data is placed under data
, 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 in Ts
and js
The writing is similar
Using combined API
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 of5101c0cdbdc49998c642c71f6b6410a82cacc6d41bbb37262a98f745aa00fbf0
The component template is compiled into an inline function, and the code in 5101c0cdbdc49998c642c71f6b6410a82cacc6d41bbb37262a98f745aa00fbf0
is in the same scope
Unlike the option-styleAPI
Need to rely on this
context object to access properties. The compiled template can directly access the variables defined in 5101c0cdbdc49998c642c71f6b6410a82cacc6d41bbb37262a98f745aa00fbf0
without the need for optional API , The agent
in the instance object uses the combined API
, 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 of vue3
can still be achieved
OptionalAPI
and combinedAPI
can be mixed. If you want to use the combined API
in the optional API
, it is based on Vue3
or vue2 Versions after .7
can use the combined API through the setup()
option
In the official documentation, it is mentioned that in an option-based API
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, use setup()
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 combined API
are two different programming styles provided by Vue
. Before the vue2.7
version, option style was used API
, responsive data needs to be mounted under data, and methods need to be mounted under methods
. In the combined API, you only need to add ## in the script tag. After #setup is marked, it means that it has a combined
API usage environment. If
API from vue
Function, variables and functions defined in
script can 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!