1. Disadvantages of Options API (optional API)
1.1 What is an Optional API
existThe way to write components is to use
Options API
, Its characteristic is to write corresponding functional modules in the corresponding properties.
for exampledata
Define data inmethods
Define methods incomputed
Define the computed properties,watch
The listening attribute changes.
Life cycle hooks also belong toOptions API
(OptionalAPI
)。
1.2 Disadvantages of Optional API
- When we implement a certain function, the code logic corresponding to this function will be split into various properties.
When components become large and complex, the list of logical concerns will grow, and the logic of the same function will be split and dispersed.
Especially for those who didn't write these components at the beginning (those who read the components), the code for this component is difficult to read and understand.
- Fragmented code uses to understand and maintain this complex component and it becomes very difficult to hide potential logic problems.
- When dealing with a single logical concern, it is necessary to constantly jump to the corresponding code block, increasing the cost of code maintenance.
2. Composition API (combination API) overview
2.1 The role of Composition API
It would be better if the code related to the same logical concern was collected together, and that'sComposition API
Things you want to do.
Vue Composition API
Can be referred to asVCA
。
2.2 The encoding location of the Composition API
Provided
setup
Functions to write various combinationsAPI
。
setup
In fact, it is another option for the component, but this option can be used to replace most other options.API
Options.
for examplemethods
、computed
、watch
、data
, various life cycle hook functions, etc.
3. Parameters and return value of the setup function
3.1 Parameters of the setup function
The setup function mainly consists of two parameters:
-
props
: The properties passed by the parent component will be placed inprops
In the object-
props
Types, and optionsAPI
The same rules in the props option are defined -
props
The use oftemplate
It's still possible toprops
The attributes in it are considered ordinaryVue
Use variables. - exist
setup
Used in functionsprops
, cannot be passedthis
Go and get it
-
-
context
: Also calledSetupContext
,yessetup
The context object of a function, which is mainly composed of three properties-
attrs
: All nonprops
Properties of -
slots
: The slot passed by the parent component will be effective when returning as a rendering function -
emit
: When an event is required to be issued within the component, emit will be used - Mainly because
setup
Not accessible in the functionthis
, so it cannot passthis.$emit
Publish an event
-
3.2 The return value of the setup function
setup
The return value can be used as a substitute fordata
Options, thereforesetup
The return value can be in the templatetemplate
Used in.
<script> import { ref } from 'vue' export default { setup() { // Define the content of the counter // The data defined by default is not responsive data. Using ref can make the data responsive let counter = ref(100) return {counter} } } </script>
setup
The return value can be used as a substitute formethods
Methods defined in
<script> import { ref } from 'vue' export default { setup() { // Define the content of the counter // The data defined by default is not responsive data. Using ref can make the data responsive let counter = ref(100) const increment = () => { ++ () } return {counter, increment} } } </script>
4. How to define responsive data in setup
4.1 reactive function
Code example:
<template> <div> <h2>account: {{ }}</h2> <h2>password: {{ }}</h2> <!-- Not usedreactiveFunction time,Click this button,Able to modify data,But it cannot be rendered on the page --> <button @click="changeAccount">修改account</button> </div> </template> <script> // 1.Introduce reactive functions import { reactive } from 'vue' export default { setup() { // 2. Use reactive functions: Define responsive data of complex types const account = reactive({ username: "Zhang San", password: "666666" }) function changeAccount() { = "kobe" } // 3. Return the defined data return {account, changeAccount} } } </script>
From the code example, you can know that using the reactive function, you can pay attention to three steps:
- from
Vue
Introducedreactive
function - Make the complex data type to be defined (Object or array) Incoming
reactive
function,reactive
The return value of the function is responsive data. - Forgot to be
setup
Returns in the function can only be used on the template
Why does the data become reactive after adding the reactive function:
When we usereactive
After the function processes our data, it will be collected in dependencies when the data is used again.
When the data changes, all collected dependencies perform corresponding responsive operations.
OptionalAPI
In-housedata
The complex data in the options are also handed over to the bottom layer.reactive
Functions program their responsive objects.
4.2 ref function
1) Basic use of ref function
reactive
Functions have restrictions on the type passed in, and they require that the object or array type must be passed in.
If you pass in a basic data type, for exampleString
、Number
、Boolean
Wait and you will report a warning:
value cannot be made reactive : xxx
Vue3
Provide us with another oneref
function.
ref
The function returns a mutable responsive object, which maintains its internal value as a responsive reference, which is alsoref
The origin of the name.
The value inside it isref
ofvalue
The properties are maintained, so they are usedref
Function-defined variables need to be used fromvalue
Attribute value.
Code example:
<template> <div> <!-- By default, intemplateUsed inrefhour, vueIt will be automatically unpacked(Take it outvalue) --> <h2>Current count: {{ counter }}</h2> <button @click="increment">+1</button> <button @click="counter++">+1</button> </div> </template> <script> // 1.Introduce ref function import { ref } from 'vue' export default { setup() { // Function: Mainly defines simple types of data (you can also define complex types of data) const counter = ref(0) function increment() { ++ } // 3. Return the defined data return {counter, increment} } } </script>
2) Ref shallow unpacking
<template> <div> <!--ref shallow unpacking (Meaning is torefWhen a variable is placed in another object, there will be two situations below.)--> <!-- No need to write when using.value --> <h2>Current count: {{ }}</h2> <!-- Need to write when modifying.value --> <button @click="++">+1</button> </div> </template> <script> // 1.Introduce ref function import { ref } from 'vue' export default { setup() { // Function: Mainly defines simple types of data (you can also define complex types of data) const counter = ref(0) const info = {counter} // 3. Return the defined data return {counter} } } </script>
Note:
- Introduced in templates
ref
When the value defined by the function,Vue
It will automatically help us unpack - Unpacking is
Vue
Automatically removeref
The variable defined by the functionvalue
value - Therefore, the user does not need to pass the template
Use the method
- exist
setup
Inside the function,ref
The value defined by the function is aref
Quote, so you need to useTo operate it in a way
- about
ref
shallow unpacking - Directly in
template
Used inref
Variables will be automatically unpacked - If
ref
The following situation will be found in a variable in an object- When used, it will be automatically unpacked
- When modifying, no automatic unpacking is performed, so it is necessary to use
value
Attribute to get value
4.3 About how to choose reactive functions and ref functions
1) Scenario where reactive function is selected
-
reactive
The definition of the function applied to local data. Local data means that this data does not originate from the server. -
reactive
There is a certain connection between multiple attributes of complex data defined by functions.
import {reactive} from 'vue' const user = reactive({ username: 'Zhang San', password: '123456' })
For example, collecting data in a form is a scenario that is very suitable for using reactive functions.
2) Scenario where ref function is selected
Define local simple types of data
import {ref} from 'vue' const message = ref('hello ref')
Define the data obtained from the server
import {ref} from 'vue' const music = ref([]) // Define a local arrayconst serverMusicList = ['Little Star', 'The insects fly'] // Simulate the data obtained from the server = serverMusicList // Assign data to music variables
This is a saying of experience. Many excellent open source projects are also used in this way. The documentation does not specify what situations are used.
This is actually a problem that programmers should consider by themselves
5. The use of one-way data flow and readonly
5.1 One-way data flow specification
1) What is a one-way data flow specification
The object data passed to the child component by the parent component can only be used and not allowed to be modified.
Although it can be modified, it violates the principle of one-way data flow.
If you really want to modify this data, you should issue an event, let the parent component listen to the event, and then modify it in the parent component.
2) Why follow this principle
In the future, there may be many child components in the project, and one data of the parent component may be passed to multiple child components.
Since it is passed a reference to the data object, modifying the data in one of the subcomponents will cause all references to be affected.
Moreover, it is difficult to know which location of the data was modified during maintenance.
There are many similar concept specifications in other places:
-
react
middle -
react
There is an important principle: any component should be like a pure function and cannot be modified.props
-
js
middle - exist
js
There are similar principles in it, familiarjs
The concept of a pure function may be known. A pure function means that the function does not modify the passed parameters.
If these specifications are not followed, the code can indeed implement functions. But the maintenance will be very poor in the future, whoever tries will know.
5.2 Readonly use
When passing data to a component, if you want the component to use the passed content. But when they are not allowed to be modified, it can be usedreadonly
Now.
Because the principle of one-way data flow isIt cannot be avoided from the code at any time. If a programmer doesn't know this principle at all.
It is possible to write code that is difficult to maintain.
andProvided
readonly
Functions avoid this problem from the encoding level.
<template> <!-- Give componentshomePass a read-only data --> <home :info="readonlyInfo" /> </template> <script> import { readonly } from 'vue' setup() { // Locally define multiple data that needs to be passed to subcomponents const info = reactive({ name: "Zhang San", age: 25, height: 1.78 }) // Use readOnly to wrap info const roInfo = readonly(info) return {roInfo} } </script>
readonly
The returned objects are not allowed to be modified; howeverreadonly
The original object processed is allowed to be modified.
For example, for statementsconst info = readonly(obj)
,info
Objects are not allowed to be modified.
whenobj
When modified,readonly
Returnedinfo
The object will also be modified;
But we can't modifyreadonly
Returned objectinfo
;
If the code itself adheres to the principle of one-way data flow, it can also be used without
Other points of note for readonly:
-
readonly
The read-only proxy that returns the original object - That is, it's still one
Proxy
, this is aproxy
ofset
The method is hijacked and cannot be modified - Common in development
readonly
The method will pass in three types of parameters: - Type 1: Normal object
- Type 2:
reactive
Returned object - Type 3:
ref
Object of
6. Reactive-related judgment API
-
isProxy
: Check whether the object isreactive
orreadonly
Createdproxy
-
isReactive
: Check whether the object isreactive
Responsive proxy created - If the proxy is
readonly
Built, but wrapped byreactive
Another proxy created, it will returntrue
-
isReadonly
: Check whether the object isreadonly
A read-only proxy created. -
toRaw
:returnreactive
orreadonly
The original object of the proxy (Present references to the original object are not recommended. Please use with caution) -
shallowReactive
: Create a responsive proxy that tracks itselfproperty
Responsiveness
But deep responsive transformations of nested objects (deep or native objects).
shallowReadonly
: Create aproxy
, make its ownproperty
For read only
But the deep read-only conversion of nested objects is not performed (deeply readable and writable)
These may not be used much, but you should also understand
7. Ref other APIs
7.1 toRefs
useES6
deconstructed syntax,reactive
The returned object is deconstructed to obtain the value, and the data will no longer be responsive.
const info = reactive({ name: "Zhang San", age: 25, height: 1.78 })
ES6 deconstruction:
const {name, age, height} = info;
Data loss responsiveness
toRefs deconstruction:
const {name, age, height} = toRefs(info);
The data remains responsive after deconstruction
7.2 unref
Used to obtain aref
Quotevalue
。
- If the parameter is a
ref
, then return the internal value, otherwise return the parameter itself - This is also
val = isRef(val) ? : val
Syntax sugar function 7.3 isRef
Determine whether the value is a ref object.
7.4 shallowRef
Create a shallow layerref
Object.
7.5 triggerRef
Manual trigger andshallowRef
Creates a responsive form of an object.
This is the article about the detailed explanation of the Vue combination API-setup definition of responsive data. For more related Vue combination API setup content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!