1. Vue3 profile
- Vue. Js version 3.0 was released on 18 September 2020.
- Over 2 years, 2600+ submissions, 30+ RFCS, 600+ PR, 99 contributors
- Tags on Github: github.com/vuejs/vue-n…
2. What does Vue3 bring
1. Performance improvement
- Package size reduced by 41%
- Initial rendering is 55% faster and updated rendering is 133% faster
- Memory reduced by 54%
2. Upgrade the source code
- Use Proxy instead of defineProperty to implement responsiveness
- Rewrite virtual DOM implementation and tree-shaking
3. Embrace the TypeScript
- Vue3 supports TypeScript better
4. New features
-
Composition API
- The setup configuration
- Ref and reactive
- Watch and watchEffect
- Dojo.provide and inject
-
New built-in components
- Fragment
- Teleport
- Suspense
-
Other changes
- New lifecycle hooks
- The data option should always be declared as a function
- Removed keyCode support as a V-ON modifier
1. Create a Vue3.0 project
1. Use vue-CLI to create a vm
The official document: cli.vuejs.org/zh/guide/cr…
Check the @vue/ CLI version and ensure that the @vue/ CLI version is above 4.5.0
vue --version
Install or upgrade your @vue/ CLI
npm install -g @vue/cli
# # to create
vue create vue3_test
# # start
cd vue3_test
npm run serve
Copy the code
2. Create the vm using Vite
The official document: v3.cn.vuejs.org/guide/insta…
Vite official website: vitejs.cn
- What is a Vite? — A new generation of front-end building tools.
- Advantages:
- Development environment, no packaging operation, fast cold start.
- Lightweight fast thermal overload (HMR).
- True on-demand compilation, no longer waiting for the entire application to compile.
- Traditional build vs. Vite build
## Create project
npm init vite-app <project-name>
Enter the project directory
cd <project-name>
# install dependencies
npm install
# # to run
npm run dev
Copy the code
Common Composition API
The official document: v3.cn.vuejs.org/guide/compo…
1. Prologue setup
- Understanding: a new configuration item in Vue3.0 with a value of a function.
- Setup is the “stage” for all Composition apis.
- The data, methods, and so on used in components are configured in Setup.
- The setup function returns two values:
- If an object is returned, the attributes and methods in the object can be used directly in the template. (Focus!)
- If a render function is returned: then you can customize the render content. (understand)
- Note:
- Do not mix with the Vue2. X configuration
- Vue2. X configuration (Data, Methos, computed…) You can access properties and methods in setup.
- But you can’t access the Vue2. X configuration (data, methos, computed…) in SETUP. .
- If the same name exists, setup takes precedence.
- Setup cannot be an async function because the return value is no longer a return object, but a promise, and the template does not see the properties in the return object. You can also return a Promise instance later, but it needs to work with Suspense and asynchronous components.
- Do not mix with the Vue2. X configuration
2. Ref function
- Function: Define a reactive data
- Grammar:
const xxx = ref(initValue)
- Create a reference object (ref object) that contains responsive data.
- Operating data in JS:
xxx.value
- To read data from a template:
<div>{{xxx}}</div>
- Remark:
- The data received can be either a primitive type or an object type.
- Basic types of data: Reactive is still dependent
Object.defineProperty()
theget
withset
The finished. - Object type data: internal“Help”A new function in Vue3.0 —
reactive
Function.
3. The reactive function
- What it does: Define aObject typeReactive data (basic type do not use it, use it
ref
Function) - Grammar:
Const proxy = Reactive (source object)
Receives an object (or array) and returns oneProxy object (Proxy instance object, Proxy object for short) - Reactive defines reactive data as “deep.”
- Internal es6-based Proxy implementation, through the Proxy object to operate the internal data of the source object.
4. Responsivity principle in Vue3.0
The response of vue2. X
-
Implementation principle:
-
Object types: Intercepts reading and modifying attributes via Object.defineProperty() (data hijacking).
-
Array types: Interception is implemented by overriding a series of methods that update an array. The array change method is wrapped.
Object.defineProperty(data, 'count', { get() {}, set(){}});Copy the code
-
-
Existing problems:
- The interface will not be updated when adding or deleting properties.
- Modify the array directly by subscript, the interface does not automatically update.
Responsiveness of Vue3.0
- Implementation principle:
-
Proxy: Intercepts the change of any attribute in the object, including reading and writing of attribute values, adding and deleting attributes.
-
Reflect: Operates on the properties of the source object.
-
Proxy and Reflect as described in the MDN documentation:
-
Proxy:developer.mozilla.org/zh-CN/docs/…
-
Reflect:developer.mozilla.org/zh-CN/docs/…
new Proxy(data, { // Intercepts reading property values get(target, prop) { return Reflect.get(target, prop); }, // Intercepts setting property values or adding new properties set(target, prop, value) { return Reflect.set(target, prop, value); }, // Intercepts delete attributes deleteProperty(target, prop) { return Reflect.deleteProperty(target, prop); }}); proxy.name ='tom'; Copy the code
-
-
5. Reactive contrast ref
- Comparison from the point of view of defining data:
- Ref is used to define basic type data.
- Reactive is used to define object (or array) type data.
- Note: ref can also be definedObject (or array) type dataIt will automatically pass through internally
reactive
toProxy objects.
- From the perspective of principle:
- Ref by
Object.defineProperty()
theget
withset
To achieve responsiveness (data hijacking). - Reactive implements reactive (data hijacking) using proxies, and reflects manipulates data within the source object.
- Ref by
- From the perspective of use:
- Data defined by ref: operation dataNeed to be
.value
To read data directly from the templateDon’t need.value
. - Data defined by Reactive: Operating data and reading data:All don’t need
.value
.
- Data defined by ref: operation dataNeed to be
6. Two notes to Setup
- The timing of setup execution
- Execute once before beforeCreate, this is undefined.
- The parameters of the setup
- Props: Is an object containing properties that are passed from outside the component and declared internally to be received by the component.
- Context: context object
- Attrs: the value is an object containing: properties passed from outside the component but not declared in the props configuration, equivalent to
this.$attrs
. - Slots: indicates the received slot content
this.$slots
. - Emit: a function that distributes custom events, equivalent to
this.$emit
.
- Attrs: the value is an object containing: properties passed from outside the component but not declared in the props configuration, equivalent to
7. Calculate properties and monitor
1. com puted function
-
This function is consistent with computed configuration in vue2. x
-
writing
import {computed} from 'vue' setup(){...// Calculate attributes - short for let fullName = computed(() = >{ return person.firstName + The '-' + person.lastName }) // Calculate attributes -- complete let fullName = computed({ get(){ return person.firstName + The '-' + person.lastName }, set(value){ const nameArr = value.split(The '-') person.firstName = nameArr[0] person.lastName = nameArr[1]}})}Copy the code
2. Watch function
-
The function is the same as that configured on Watch in vue2. x
-
Two little pits:
- Monitoring reactive data defined by Reactive: oldValue cannot be obtained correctly, forcing deep monitoring (deep configuration failure) enabled.
- The deep configuration is valid when monitoring an attribute in reactive data defined by Reactive.
// Monitor reactive data defined by ref watch( sum, (newValue, oldValue) = > { console.log('Sum changes', newValue, oldValue); }, { immediate: true});// Monitor reactive data defined by multiple refs watch([sum, msg], (newValue, oldValue) = > { console.log('Sum or MSG changes', newValue, oldValue); }); // Monitor reactive data defined by Reactive // If watch is monitoring reactive data, oldValue cannot be obtained correctly!! // If watch monitors reactive data, deep monitoring is forcibly enabled watch( person, (newValue, oldValue) = > { console.log('Person has changed', newValue, oldValue); }, { immediate: true.deep: false});// The deep configuration here no longer works // Monitor a property in reactive data defined by Reactive watch( () = > person.job, (newValue, oldValue) = > { console.log('Person's job has changed', newValue, oldValue); }, { immediate: true.deep: true});// Case 5: Monitor some properties in reactive data defined by Reactive watch( [() = > person.job, () = > person.name], (newValue, oldValue) = > { console.log('Person's job has changed', newValue, oldValue); }, { immediate: true.deep: true});// Special circumstances watch( () = > person.job, (newValue, oldValue) = > { console.log('Person's job has changed', newValue, oldValue); }, { deep: true});The deep configuration is valid because you are monitoring a property in an object defined by Reactive Copy the code
3. WatchEffect function
-
The watch routine is to specify both the monitoring properties and the monitoring callbacks.
-
The watchEffect formula is this: you don’t have to specify which property to watch, just watch which property is used in the monitored callback.
-
WatchEffect is a bit like computed:
- But computed values care about computed values (the return value of the callback function), so you have to write the return value.
- WatchEffect is more about the procedure (the body of the callback function), so you don’t write the return value.
// Whenever the data used in the watchEffect callback changes, the callback is reexecuted. watchEffect(() = > { const x1 = sum.value; const x2 = person.age; console.log('watchEffect configured callback executes'); }); Copy the code
8. Life cycle
- Vue3.0 can continue to use lifecycle hooks from Vue2.x, but two have been renamed:
beforeDestroy
renamedbeforeUnmount
destroyed
renamedunmounted
- Vue3.0 also provides lifecycle hooks in the form of Composition API, which correspond to Vue2. X hooks as follows:
beforeCreate
= = = >setup()
created
= = = = = = = >setup()
beforeMount
= = = >onBeforeMount
mounted
= = = = = = = >onMounted
beforeUpdate
= = = >onBeforeUpdate
updated
= = = = = = = >onUpdated
beforeUnmount
= = >onBeforeUnmount
unmounted
= = = = = >onUnmounted
9. Customize hook functions
-
What is a hook? This is essentially a function that encapsulates the Composition API used in setup functions.
-
Similar to mixins in vue2. X.
-
Advantages of custom hooks: Reusing code makes the logic in setup much clearer and easier to understand.
10.toRef
-
Creates a ref object whose value points to an attribute in another object.
-
Const name = toRef(person,’name’)
-
Application: When an attribute in a reactive object is individually provided for external use.
-
Extension: toRefs has the same functionality as toRef, but can batch create multiple REF objects, syntax: toRefs(person)
Other Composition apis
1. ShallowReactive shallowRef
-
ShallowReactive: Handles only the responsivity (shallow responsivity) of the outermost attributes of the object.
-
ShallowRef: Only primitive data type responsivity is handled, not object responsivity.
-
When to use it?
- If you have an object data, the structure is deep, but changes only when the outer properties change === => shallowReactive.
- If you have an object data, subsequent functions do not modify the properties in that object, but instead generate a new object to replace ===> shallowRef.
2. With shallowReadonly readonly
- Readonly: makes responsive data read-only (deep readonly).
- ShallowReadonly: Makes a responsive data read-only (shallow read-only).
- Application scenario: Data is not modified.
3. ToRaw markRaw
- ToRaw:
- Role: will a by
reactive
The generatedResponsive objecttoOrdinary objects. - Usage scenario: Used to read a common object corresponding to a responsive object. All operations on this common object do not cause page updates.
- Role: will a by
- MarkRaw:
- Function: Marks an object so that it will never be a reactive object again.
- Application Scenarios:
- Some values should not be set to reactive, such as complex third-party libraries.
- Skipping reactive transformations can improve performance when rendering large lists with immutable data sources.
4.customRef
-
What it does: Creates a custom REF with explicit control over its dependency trace and update trigger.
-
Achieve anti-shake effect:
<template> <input type="text" v-model="keyword" /> <h3>{{ keyword }}</h3> </template> <script> import { ref, customRef } from 'vue'; export default { name: 'Demo'.setup() { // let keyword = ref('hello') // use the built-in ref prepared by Vue // define a myRef function myRef(value, delay) { let timer; // Implement customization via customRef return customRef((track, trigger) = > { return { get() { track(); // Tell Vue that the value needs to be "traced" return value; }, set(newValue) { clearTimeout(timer); timer = setTimeout(() = > { value = newValue; trigger(); // Tell Vue to update the interface}, delay); }}; }); }let keyword = myRef('hello'.500); // Use programmer-defined ref return{ keyword, }; }};</script> Copy the code
5. Dojo.provide and inject
-
Function: Implements communication between ancestor and descendant components
-
Formula: The parent component has a provide option to provide data, and the descendant component has an Inject option to start using that data
-
Specific writing:
-
Ancestor components:
setup(){...let car = reactive({name:'Mercedes'.price:'400000'}) provide('car',car) ...... } Copy the code
-
In descendant components:
setup(props,context){...const car = inject('car') return {car} ...... } Copy the code
-
6. Judgment of responsive data
- IsRef: Checks whether a value is a ref object
- IsReactive: Checks whether an object is created by
reactive
Create a responsive proxy - IsReadonly: Checks whether an object is created by
readonly
The read-only agent created - IsProxy: Checks whether an object is created by
reactive
orreadonly
Method to create an agent
4. Advantages of Composition API
1. Problems with the Options API
Using traditional OptionsAPI, to add or modify a requirement, you need to modify it in data, methods, and computed, respectively.
2.Com Position API advantages
We can organize our code and functions more elegantly. Keep the code of related functions organized.
New components
1.Fragment
- In Vue2: Components must have a root tag
- In Vue3, components can have no root tag and contain multiple tags inside a Fragment virtual element
- Benefits: Reduced label hierarchy and memory footprint
2.Teleport
-
What is Teleport? Teleport is a technology that moves our component HTML structure to a specific location.
<div v-if="isShow" class="mask"> <div class="dialog"> <h3> I am a popover </h3> < button@click ="isShow = </button> </div> </div> </teleport>Copy the code
3.Suspense
-
Render some extra content while waiting for asynchronous components to make the application a better user experience
-
Use steps:
-
Asynchronously importing components
import { defineAsyncComponent } from 'vue'; const Child = defineAsyncComponent(() = > import('./components/Child.vue')); Copy the code
-
Wrap components in Suspense and configure default and fallback
<template> <div class="app"> <h3> I am app component </h3> <Suspense> <template V-slot :default> <Child /> </template> <template V-slot :fallback> <h3> Loading..... </h3> </template> </Suspense> </div> </template>Copy the code
-
Sixth, other
1. Global API transfer
-
Vue 2.x has a number of global apis and configurations.
-
For example, register global components, register global directives, etc.
// Register the global component Vue.component('MyButton', { data: () = > ({ count: 0 }), template: '<button @click="count++">Clicked {{ count }} times.</button>' }) // Register the global directive Vue.directive('focus', { inserted: el= > el.focus() } Copy the code
-
-
Changes to these apis have been made in Vue3.0:
-
Adjust the global API, i.e. Vue.xxx, to the application instance (app)
2. X global API ( Vue
)3.x instance API ( app
)Vue.config.xxxx app.config.xxxx Vue.config.productionTip remove Vue.component app.component Vue.directive app.directive Vue.mixin app.mixin Vue.use app.use Vue.prototype app.config.globalProperties
-
2. Other changes
-
The data option should always be declared as a function.
-
Excessive class name changes:
-
Vue2. X
.v-enter..v-leave-to { opacity: 0; } .v-leave..v-enter-to { opacity: 1; } Copy the code
-
Vue3. X
.v-enter-from..v-leave-to { opacity: 0; } .v-leave-from..v-enter-to { opacity: 1; } Copy the code
-
-
Removed keyCode as v-on modifier and also removed support for config.keycodes
-
Remove the V-on. native modifier
-
Bind events in the parent component
<my-component v-on:close="handleComponentEvent" v-on:click="handleNativeClickEvent" /> Copy the code
-
Declare custom events in child components
<script> export default { emits: ['close'], }; </script> Copy the code
-
-
Remove the filter
Filters While this may seem convenient, it requires a custom syntax to break the assumption that expressions in braces are “just JavaScript”, and there are not only learning costs, but implementation costs too! It is recommended to replace filters with method calls or computed properties.
Learning never ends, CV never stops, because I just started learning Vue3 recently, and I often like to browse the front end video of Silicon Valley, this article is from THE video notes of Yu Ge of BEep station. Personally feel very easy to understand, can not help but dry up the porter, with the summative documents, directly moved over, in order to prepare for a quick review, finally carry a video link address, can go to the video to learn together, do not spray, do not move bricks is not easy, thank you