It’s been over a year since Vue3 was released, and I don’t know if you’re using Vue3 in your daily development. Let’s take a look at the differences between Vue3 and previous versions.
Ve2. X uses an optional API, while Vue3. X uses a composite API.
What is the Options API
-
This is the option API notation we used in the Vue2. X project
- Code style: data options write data, methods options write functions… , a functional logic of code dispersion.
- Advantages: Easy to learn and use, the location of the code has been agreed
- Disadvantages: poor code organization, similar logic (function) code is not easy to reuse, logic complex code is not easy to read.
What is the Composition API: Composition API
- Organizing your code by function makes it easier to reuse functionality later.
By creating Vue components, we can extract the repetitive parts of the interface, along with their functionality, into reusable snippet of code. This alone will take our application a long way in terms of maintainability and flexibility. However, our experience has shown that this alone may not be enough, especially if your application becomes very large — think hundreds of components. Sharing and reusing code becomes especially important when dealing with large applications like this. Organizing logic with component options (Data, computed, Methods, watch) is often effective. However, as our components start to get bigger, the list of logical concerns grows. This can lead to components that are hard to read and understand, especially for those who didn’t write them in the first place.
This is an example of a large component whereLogical concernGroup by color.
This fragmentation makes it difficult to understand and maintain complex components. The separation of options masks a potential logical problem. In addition, when dealing with a single logical concern, we must constantly “jump” to the option blocks of the related code.
It would be even better if you could collect code related to the same logical concern. And that’s exactly what composite apis allow us to do.
1. Composite API basics
So where do we use it? In Vue components, we call this location setup
setup
Component options
Usage details:
setup
Is a new component option that serves as a starting point for using composite apis in components.- From a component lifecycle perspective, it executes before the component instance is created
BeforeCreate vue2. X
The execution. - This means that in the
setup
In the functionthis
Not yet a component instance,this
At this point isundefined
- The data and functions that need to be used in the template need to be in the
setup
To return.
Demo code:
< the template > < div > < div > the setup function usage < / div > < hr > < div > {{MSG}} < / div > < div > {{info}} < / div > < div > < button @click='handleClick'> click </button> </div> </template> <script> export default {name: 'App', // Vue3 can still use data from data, but not recommended (this is the option API) data () {return {info: 'nihao'}}, setup () {// Trigger before beforCreate/created life cycle // Vue3 beforCreate/created declaration cycle function is deprecated, // This cannot be accessed at this time, // console.log(this) // Define the event function const handleClick = () => {console.log('click')} // The data returned here is used for the template: Return {MSG: 'hello', handleClick}}} </script> <style lang="less"> </style>Copy the code
Conclusion:
- The Setup option is the basis for implementing the composite API
- The trigger time is before the beforeCreate
- The beforCreate/created declaration cycle function in Vue3 is deprecated and has been replaced by setup
- This cannot be accessed at this time because the component instance has not yet been created
- The return value from setup is used to provide data and methods to the template
- Templates can still get data from Data, but using data is not recommended.
2. Composition API- Life cycle
- Review the vue2. X lifecycle hook functions:
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- beforeDestroy
- destroyed
- Recognize vue3.0 lifecycle hook functions
setup
Before creating an instanceonBeforeMount
Mount the DOMonMounted
Mount after the DOMonBeforeUpdate
Before updating componentsonUpdated
After updating componentsonBeforeUnmount
Before unloading and destructiononUnmounted
After unloading and destruction
Conclusion:
- The function of the Vue3 lifecycle has changed
- Remove two: beforeCreate and created, and add setup
- Method names have changed: The method name is preceded by an ON and is humped in the middle
- Changes the life cycle of an unmounted component: onBeforeUnmount, onUnmounted
- The same life cycle can trigger multiple times
3. Combine apI-Reactive functions
Reactive is a function that defines a complex data type as reactive data.
<script> import {reactive} from 'vue' export default {name: // let MSG = 'hello' // reactive(const obj = reactive({MSG: 'hello', info: 'hi' }) const handleClick = () => { // msg = 'nihao' // console.log(msg) obj.msg = 'nihao' } return { obj, handleClick } } } </script> <style lang="less"> </styleCopy the code
Conclusion:
- The normal data that Setup returns by default is not reactive
- If you want your data to be reactive, one way to do this is to wrap the data around reactive methods
4. Combine apI-toref functions
Define reactive data:
- ToRef is a function that converts a property of a responsive object into a single responsive data with associated values.
<template> <div> <div> data response </div> <hr> <! - < div > {{obj. MSG}} < / div > -- > < div > {{MSG}} < / div > < div > {{info}} < / div > < div > < button @ click = 'handleClick' > click < / button > </div> </div> </template> <script> import { reactive, toRef } from 'vue' export default { name: 'App', setup () {// Request: obj = reactive({MSG: 'hello', info: Const MSG = toRef(obj, 'MSG ') const info = toRef(obj,' MSG ') 'info') const handleClick = () => {obj. MSG = 'nihao' obj. Info = 'coniqiwa'} msg, info, handleClick } } } </script> <style lang="less"> </style>Copy the code
Conclusion: The toRef method can extract a single attribute from an object and ensure responsiveness
5. Combine apI-Torefs functions
ToRefs is a function that converts all attributes of a responsive object (some of them) into a single responsive data. The object becomes a normal object and its values are associated.
6. Combine apI-ref functions
The ref function, often used for simple data types defined as reactive data
- When modifying a value and getting a value,.value is required
- The.value can be omitted if ref is used to declare reactive data in the template
Code demo: <template> <div> <div> <hr> <div>{{count}}</div> < button@click ='handleClick'> </button> </div> </div> </template> <script> import { ref } from 'vue' export default { name: Const count = ref(0) const obj = ref({MSG: const count = ref(0) const obj = ref({MSG: }) const handleClick = () => {// ref defines data, Value += 1 console.log(obj.value.msg)} return {count, handleClick } } } </script> <style lang="less"> </style>Copy the code
conclusion
- If it is primitive type data, you can define it using ref
- Ref can actually define an object, but the value attribute is required to access it
-
Data response
- Normal data returned directly from SETUP is not reactive
- Wrapped around reactive objects can become responsive data
- To simplify access to objects (without prefixes), optimization can be done using toRef
- To get multiple properties in an object, you can use toRefs to simplify things further
- For simple data types, the ref definition is more appropriate