1.1 Creating a Vue3.0 Project
1.1.1 Using vuE-CLI To Create a vm
The official document: cli.vuejs.org/zh/guide/cr…
## Check @vue/cli NPM install -g @vue/cli ## Create vue create vue_test ## start CD vue_test npm run serveCopy the code
1.2.2 Creating a Vm using Vite
The official document: v3.cn.vuejs.org/guide/insta…
Vite official website: vitejs.cn
## install NPM run dev ## install NPM run dev ## install NPM run devCopy the code
2.1 Common Composition API
The official document: v3.cn.vuejs.org/guide/compo…
2.1.1 the setup
< h1 > {{name}} < / h1 > / / foo < button @ click = "say" > button < / button > / / hello -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the export default { name: 'App', setup () {let name='foo' // define a constant function function say() {// define a function console.log('hello')} return {name, // define a constant, Setup is a new configuration item of vue3, the value is a function. Data,methods, hooks, etc are configured in it. Setup is not reactive, and the ref function uses 2. Try not to mix with vue2 syntaxCopy the code
Points to note:
The setup execution time is executed once before the beforeCreate, this is undefined. The setup parameter is an object that contains properties passed from outside the component and declared to be received inside the component. Attrs = $attrs slots = this.$slots emit: Function to distribute custom events of enclosing $emit -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- props: [] / / need to receive it, Setup (props,context) {context.attrs context.slotscontext. emit //setup does not have this, only content}Copy the code
2.1.2 ref function
Define a reactive data syntax: let XXX = ref(initValue) //initValue is the initial valueCopy the code
< h1 > {{name}} < / h1 > < h1 > {{person. Sex}} < / h1 > < h1 > {{person. Age}} < / h1 > < button @ click = "changeName" > button < / button > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the import {ref} from 'vue' setup () {let name = ref (' foo ') / / processing basic data types let person = ref ({/ / processing object data types name:'foo', Age: 18}) function changeName () {name. The value = 'bar' person. The value. The sex = 'male' person. The value, the age = 20} return {name, person, ChangeName}} Note: ref can receive basic types and object types. The value can be set to. Value in template. note: Ref can receive object types but should not use themCopy the code
2.1.3 reactive function
Function: Define an object type let XXX = reactive(initValue) //initValue as the initial valueCopy the code
<h1>{{name}}</h1> <h1>{{person.name}}</h1> <h1>{{person.age}}</h1> <h1>{{arr}}</h1> <button @ click = "changeName" > button < / button > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the setup () {/ / let name = reactive (' foo ') warning, Let person=reactive({name:'foo', age:18 }) let arr=reactive(['1','2','3']) function changeName() { person.name='bar' person.age=20 arr[0]='4' } return {arr, person, changeName}} reactive only accepts values from object types 2.js and templateCopy the code
3.1 Responsivity principle in Vue3.0
3.1.1 Response formula 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.
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.
Object.defineProperty(data, 'count', {
get () {},
set () {}
})
Copy the code
3.1.2 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.
Get (target, prop) {return reflect. get(target, prop)}, // Add a new attribute set (target, prop) Prop, value) {return reflect. set(target, prop, value)}, // prop) { return Reflect.deleteProperty(target, prop) } })Copy the code
4.1 Computing properties and monitoring
4.4.1 computed function
Import {computed} from 'vue' setup(){// Calculate attributes - short let fullName = computed(()=>{return person.firstName + '-' + Person.lastname}) // Compute attributes -- full let fullName = computed({get(){return person.firstName + '-' + person.lastname}, set(value){ const nameArr = value.split('-') person.firstName = nameArr[0] person.lastName = nameArr[1] } }) }Copy the code
4.1.2 watch function
Two little pits:
Monitoring reactive data defined by Reactive: oldValue cannot be obtained correctly, forcing deep monitoring (deep configuration failure) enabled.
When monitoring an attribute (object) in reactive data defined by Reactive: Deep is valid and oldValue cannot be obtained correctly.
Let sum=reactive(0) let MSG =reactive(' MSG ') let person=reactive({name:'foo', age:18, job:{s:20}}) Watch (sum,(newValue,oldValue)=>{console.log('sum changed ',newValue,oldValue)},{immediate:true}) Watch ([sum, MSG],(newValue,oldValue)=>{console.log('sum or MSG changed ',newValue,oldValue)}) /* If watch is monitoring reactive data defined by Reactive, oldValue cannot be obtained. If Watch monitors reactive data defined by Reactive, */ watch(person,(newValue,oldValue)=>{console.log('person changed ',newValue,oldValue) }, {immediate: true, deep: false}) / / deep configuration is no longer work here / / situation 4: Watch (()=>person.job,(newValue,oldValue)=>{console.log(' Person job changed ',newValue,oldValue) },{immediate:true,deep:true}) Watch ([()=> Person.job,()=> Person.name],(newValue,oldValue)=>{ Console. log(' Person job changed ',newValue,oldValue)},{immediate:true,deep:true}) // Special case Watch (()=>person.job,(newValue,oldValue)=>{console.log('person job changed ',newValue,oldValue)},{deep:true}) The deep configuration is valid because you are monitoring a property in an object defined by ReactiveCopy the code
3. WatchEffect function
// Whenever the data used in the watchEffect callback changes, the callback is reexecuted. If you don't have data, Let name=reactive('foo') watchEffect(()=>{const x1 = name. Value const x2 = person.age Console. log('watchEffect configured callback executed ')})Copy the code
5.1 Life Cycle
5.1.1 Hook Changes
BeforeDestroy is renamed to beforeUnmount DestroyedCopy the code
5.1.2 writing
Write the configuration item
setup () {},
beforeCreate() {}
created() {}
...
Copy the code
Combinatorial notation
// Create creates the beforeCreate hook and creates the beforeCreate hook and creates the beforeCreate hook. Import {onBeforeMount} from 'vue' setup () {//onBeforeCreate(()=>{}),onCreated(()=>{}) There is no design these two hooks onBeforeMount (() = > {}) onMounted (() = > {})... },Copy the code
6.1 toRef, toRefs
ToRef (obj,'obj.key') const name = toRef(obj,'obj.key'); Object property toRefs const name = toRef(obj) // Argument: the object to respond toCopy the code
ToRef instance
<h1>{{name}}</h1>
<h1>{{s}}</h1>
----------------------------
import {reactive,toRef} from 'vue'
setup () {
let person=reactive({
name:'foo',
job:{
s:20
}
})
return {
name:toRef(person,'name'),
s:toRef(person.job,'s'),
}
}
Copy the code
ToRefs instance
< h1 > {{name}} < / h1 > < h1 > {{obj. S}} < / h1 > / / can take to obj, need s, To use obj. S -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the import {reactive, toRefs} from 'vue' setup () {let person = reactive ({name: 'foo', job:{ s:20 } }) return { ... ToRefs (person) // Take the attributes of the object by extending the operator, but only one layer,}}Copy the code
7.1 Other Composition apis
7.1.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.
Use:
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.
7.1.2 readonly and shallowReadonly
Readonly: makes responsive data read-only (deep readonly).
ShallowReadonly: Makes a responsive data read-only (shallow read-only).
Application scenario: Data is not modified.
7.1.3 toRaw markRaw
ToRaw:
Function: Transforms a reactive object generated by Reactive into a normal object.
Usage scenario: Used to read a common object corresponding to a responsive object. All operations on this common object do not cause page updates.
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.
7.1.4 customRef
What it does: Creates a custom REF with explicit control over its dependency trace and update trigger.
<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') // Define a myRef function myRef(value,delay){let timer CustomRef ((track,trigger)=>{return{get(){track() // tell Vue that this value is the return value that needs to be "tracked"}, Set (newValue){clearTimeout(timer) timer = setTimeout(()=>{value = newValue trigger() // tell Vue to update interface},delay)}}})} Let keyword = myRef('hello',500) // use programmer's custom ref return {keyword}}} </script>Copy the code
7.1.5 dojo.provide and inject
Function: Implements communication between ancestor and descendant components
Application: The parent component has a provide option to provide data, and the descendant component has a Inject option to start using that data
Ancestor components:
setup(){
......
let person = reactive({name:'foo',age:18})
provide('p',person)
......
}
Copy the code
In descendant components:
setup(){
......
const car = inject('p')
return {car}
......
}
Copy the code
7.1.6 Judgment of responsive data
IsRef: checks whether a value is a REF object. IsReactive: checks whether an object is a reactive proxy created by Reactive. IsReadonly: checks whether an object is a read-only proxy created by readOnly. Check whether an object is a proxy created by a reactive or Readonly methodCopy the code
8.1 New Components
8.1.1 Teleport
//Teleport is a technology that can move our component HTML structure to a specified location. <h1> Hello </h1> </teleport>Copy the code
8.1.2 Suspense
Suspense: Async components // import {defineAsyncComponent} from 'vue' const Child = defineAsyncComponent(()=>import('./components/Child.vue'))Copy the code
Using Suspense wrap components, < x64 > < x64 > < x64 > < x64 > < x64 > < x64 > < x64 > < x64 > < x64 > < x64 > < x64 > < x64 <Child/> </template> <template V-slot :fallback> // Alternate component <h3> loading..... </h3> </template> </Suspense> </div> </template>Copy the code
9.1 other
9.1.1 Global API transfer
Vue3.0 tweaks these apis: the global API, vue.xxx, is tweaked 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 |
9.1. 2 Other changes
The data option should always be declared as a function. V -enter==>. V -enter-from,. V -leave==>. V -leave-from 3. Removed keyCode as v-on modifier and no longer supports config.keycodes 4. < my-Component V-on :close="handleComponentEvent" V-on :click="handleNativeClickEvent" /> // Child component ------------------ <script> export default {emits: ['close'] //close is a custom component, click is not written, default is v-on.native} </script> 5. Remove the filterCopy the code
Feel free to like and comment if you find it helpful. The views expressed above are personal. Please correct any errors. If you are interested in the front, welcome to my personal blog sundestiny. Making. IO/myblog /