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

Let's talk in depth about the two different writing styles of Vue components.

青灯夜游
Release: 2023-04-11 18:54:59
forward
1266 people have browsed it

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!

Let's talk in depth about the two different writing styles of Vue components.

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

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 thewatchlistener. [Related recommendations:vuejs video tutorial,web front-end development] The properties defined by

components will be exposed onthisinside 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 formulaAPIThe sample code is as follows

  
Copy after login

For the optionalAPI, it is thevue2.0writing specification. The responsive data related to the page display is mounted indataNext, the binding method is placed inmethods. It is a conventional

some option configuration parameters and a configurable

combined API ( composition API)

combinationAPI(Composition API) is a collection ofAPI

passed CombinedAPIcan be imported fromvueby 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

Thissetupis an identifier, just liketype="text/javascript", tellingvuewhat needs to be done Some processing during compilation

allows us to use the combinedAPIconcisely, such as: import and top-level inVariables or functions can be written directly using

in the template instead of declaring options to writevuecomponents. CombinedAPIis 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 ofVuewhen using the responsiveAPI

The specific code is as follows

 
Copy after login

[1]. You need to introduce the ref API function[2] from

vue

. In the logic code of the component, you need to usexxx.valueGet the value and modify

[3]. There is no need to writexxx.valuein 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 optionalAPIand the combinedAPItwo code writing styles that if the optionalAPIis used, then the page The bound responsive data needs to be mounted under thedataconfiguration option, while the binding method

needs to be placed under themethodsconfiguration 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 onthisto 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 fromvueto 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 nothisbinding.thiswill isundefined, you can access the value exposed by the combinedAPIin the optionalAPI, but not the other way around

As shown below The picture is a good comparison of the difference between optionalAPIand componentAPI

Comparison of the two styles

vue2has 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,Vue3is an upgrade and expansion ofvue2

provides two different sets of The interface is for developers to freely choose and use

OptionalAPIis centered on the component instance, with the constructor function, that is,thisas 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 thedatainstance option.

It obtains the state directly from the function, by directly accessing thevueIntroducing 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

Ifvue2is a wild horse with a tightrope, thenvue3It means breaking away from the tight horse and becoming freer

Learning Suggestions

[1].Vue2andVue3It 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 usevuein 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 usevueto build a complete single-page application, then the official recommendation is to use the combinedAPIsingle file component method Go build your own project

How to use vue3 with lower version of Vue2.7

invue3andvue2.7For versions above, you can use the combinedAPI. For lower versionsvue2.7and below, you can use the officially maintained plug-in @vue/composition-api

Invue3, the combinedAPIwill basically be used in single file components withsyntax

Combined API is not functional programming

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

combinationAPIis 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

Why there is a combined API

1. Better logic reuse

CombinedAPIcan pass combined functions To achieve more concise and efficient logic reuse, in the optionalAPIour main logic reuse mechanism ismixins, and with the combinedAPI, Can solve all the defects inmixins

2. More flexible organization of code

option-based API invue2.0In programming, you must follow the usage specifications ofvueto 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

Better type inference

CombinedAPIMainly 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 combinedAPIcode written inTsandjsThe writing is similar

Smaller production package size

Using combinedAPIis 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 inis in the same scope

Unlike the option-styleAPINeed to rely onthiscontext 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

Thinking about component-based API

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

Combined The API covers all scenarios

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 ofvue3can still be achieved

The two API programming methods can be mixed

OptionalAPIand combinedAPIcan be mixed. If you want to use the combinedAPIin the optionalAPI, it is based onVue3orvue2 Versions after .7

can use the combined API through thesetup()option

In the official documentation, it is mentioned that in an option-basedAPIIn 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,vue2projects 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.

Summary

OptionAPIand combinedAPIare two different programming styles provided byVue. Before thevue2.7version, 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 combinedAPIusage environment. If

is used specifically, you need to introduce the corresponding

API fromvueFunction, variables and functions defined inscriptcan be used directly in the template. It is more of a style change that allows the front end to better organize the logic code

(Learning video sharing:

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!

Related labels:
source:juejin.cn
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