1, setup
1. It's vue3 0 is a new configuration item in, and the value is a function.
2. setup is the stage where all composition APIs are displayed.
3. There are two return values of the setup function:
If an object is returned, the properties and methods in the object can be used directly in the template. (focus!)
If you return a rendering function: you can customize the rendering content. (understand) (not commonly used)
Note:
1. Try not to talk to vue2 X versions are mixed.
- vue2. Version x can access the properties in setup.
- setup cannot access vue2 Properties of the X version.
- If there is a duplicate name, it takes precedence
2. setup cannot be an async function, because the return value is no longer an object, but promise. The template cannot see the attributes in the return object.
3. The execution order of setup is before create, and this is undefined in setup
4. Setup (props, context) accepts two parameters
- Props: the value is an object, including the attributes passed from the outside of the component and declared and received inside the component (in fact, it is the props function of vue2.0)
- Context: context object (in which you can get 1. Attributes passed from outside the attrs component but not declared in the props configuration. 2. slots: slot content. 3. Emit: functions that distribute custom events. In the future, this.$emit cannot be written in setup, but context.emit should be written)
<template> <h2>full name:{{name}}</h2> <h2>Age:{{age}}</h2> <button @click="sayInfo">display information</button> </template> <script> export default { name: "App", setup(){ //The data at this time does not have the function of two-way binding let name = "Xiao Ming" let age = 18 // method function sayInfo(){ alert(`Hello ${name},You're great, aren't you`) } // If you want to use the method or data in setup in the template, you must return return { name,age, gender,sayInfo } // Return() = > H ('h1 ',' try ') } }; </script>
2, ref
Function: define a responsive data.
Syntax: let xxx = ref(xxx)
Note:
- ref(), the brackets can be filled with basic data type and or object type
- Filling in the basic data type will return an instance object of RefImpl. There are getter s and setter s in the RefImpl class to detect data changes.
- Fill in the data of object type: in fact, vue3 is used A new function in 0 - reactive function.
- js operation value is xxx Value, directly {{xxx}} in the template
- It should be introduced before use.
<template> <h2>full name:{{ name }}</h2> <h2>Age:{{ age }}</h2> <button @click="changeInfo">Modify information</button> </template> <script> import { ref } from "vue"; export default { name: "App", setup() { // data let name = ref("Xiao Ming"); let age = ref(18); // method function changeInfo() { name.value = "Xiao Ming"; age.value = 48; } return { name, age, changeInfo, }; }, }; </script>
3, reactive
Function: define a responsive object.
Syntax: let xxx = reactive(xxx)
Note:
- reactive(), the parenthesis should be filled with the object type
- Filling in the basic data type will return a proxy instance object.
- Fill in the data of object type: in fact, vue3 is used A new function in 0 - reactive function.
- js operation value is xxx Value, directly {{xxx}} in the template
- It should be introduced before use.
- Although the above ref () method can also fill in objects, its essence still calls the reactive method, and XXX is required for js operation Value, superfluous. Moreover, the reactive object defined by reactive () is deep-seated, and there will be no case that vue2 object data level is too deep and does not change.
<template> <h2>full name:{{ yk.name }}</h2> <h2>Age:{{ yk.age }}</h2> <h2>Hobbies:{{ yk.hobby }}</h2> <h3>Test data:{{ yk.job.a.b.c }}</h3> <button @click="changeInfo">Modify information</button> </template> <script> import { reactive } from "vue"; export default { name: "App", setup() { // data let yk = reactive({ age: 18, hobby: ["having dinner", "sleep", "Beat beans"], job: { a: { b: { c: 666, }, }, }, }); // method function changeInfo() { yk.age = 48; yk.job.a.b.c = 888; // Directly modify the array subscript to trigger the response yk.hobby[0] = "Beat beans"; } return { yk, changeInfo, }; }, }; </script>
3, Calculated attribute
And vue2 Compared with X, the function is almost the same, but the writing method is slightly changed.
<template> Last name:<input v-model="person.firstName"></input> Name: <input v-model="person.lastName"></input> full name:<input v-model="person.fullName"></input> </template> <script> //First introduce import {computed,reactive } from 'vue' export default { name: "App", setup() { let person = reactive({ firstName :"Small", lastName:"bright", fullName:"" }) //Calculation properties - Abbreviations //let fullName = computed(()=>{ // return person.firstName + '-' + person.lastName //}) //Calculation properties - complete person.fullName = computed({ get(){ return person.firstName + '-' + person.lastName }, set(value){ const nameArr = value.split('-') person.firstName = nameArr[0] person.lastName = nameArr[1] } }) return { person }; }, }; </script>
3, Calculate attribute watch
It's similar to computing attributes, but only syntactic changes in vue3 and.
Note:
- When monitoring the reactive data defined by reactive: oldValue cannot be obtained correctly and deep monitoring is forced on (deep configuration fails)
- When monitoring a property in the reactive data defined by reactive (this property must be an object): the deep configuration is valid
//Scenario 1: monitor the responsive data defined by ref watch(sum,(newValue,oldValue)=>{ console.log('sum Changed',newValue,oldValue) }) //If an object is defined with ref watch(person.value,(newValue,oldValue)=>{ console.log('person Changed',newValue,oldValue) }) //Case 2: monitor the responsive data defined by multiple ref s watch([sum,msg],(newValue,oldValue)=>{ console.log('sum or msg Changed',newValue,oldValue) }) //Scenario 3: monitor reactive defined responsive data watch(person,(newValue,oldValue)=>{ console.log('person Changed',newValue,oldValue) },{immediate:true,deep:false}) //The deep configuration here no longer works //Scenario 4: monitor an attribute in the responsive data defined by reactive watch(()=>person.job,(newValue,oldValue)=>{ console.log('person of job Changed',newValue,oldValue) },{immediate:true,deep:true}) //Scenario 5: monitor some attributes in the responsive data defined by multiple reactive watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{ console.log('person of job Changed',newValue,oldValue) },{immediate:true,deep:true}) //exceptional case //person. A job in a job is also an object watch(()=>person.job,(newValue,oldValue)=>{ console.log('person of job Changed',newValue,oldValue) },{deep:true}) //Here, the deep configuration is valid because it monitors an attribute in the object defined by the reactive element
4, watchEffect function
watch: it should indicate both the monitored attribute and the monitored callback.
watchEffect: it is unnecessary to specify which attribute to monitor, and which attribute is used in the monitored callback, so which attribute to monitor.
This function has the same function as calculating attributes, but
- However, computed focuses on the calculated value (the return value of the callback function), so the return value must be written.
- watchEffect pays more attention to the process (the function body of the callback function), so there is no need to write the return value.
//As long as the data used in the callback specified by watchEffect changes, the callback will be directly re executed. watchEffect(()=>{ const x1 = sum.value const x2 = person.age console.log('watchEffect The configured callback was executed') })
5, Life cycle hook
1,vue3. Vue2.0 can continue to be used in 0 Life cycle hooks in X, but two have been renamed:
- Change beforeDestroy to beforUnmount
- Replace destroyed with unmounted
2,vue3.0 also provides a lifecycle hook in the form of composition API, which is similar to vue2 The corresponding relationship of X hooks is as follows:
- beforeCreate======>setup()
- created==========>setup()
- beforeMount======>onBeforeMount
- mounted=========>onMounted
- beforeUpdate=====>onBeforeUpdate
- updated =========>onUpdated
- beforeUnmount ===>onBeforeUnmount
- unmounted ======>onUnmounted
6, Custom hook function
- What is hook------- It is essentially a function that encapsulates the composition API used in setup.
- Similar to vue2 mixin in X.
- Advantages of custom hook: reuse code to make the logic in setup clearer.
- emmmm feels like module import and vue2 The mixin of X is also slightly different.
Create a hook folder and create the file point js
import { reactive, onMounted, onBeforeUnmount } from "vue"; export default function() { //Realize the data related to the "dot" of the mouse let point = reactive({ x: 0, y: 0, }); //Methods of realizing mouse "dot" related function savePoint(event) { point.x = event.pageX; point.y = event.pageY; console.log(event.pageX, event.pageY); } //Realize the life cycle hook related to mouse "dot" onMounted(() => { window.addEventListener("click", savePoint); }); onBeforeUnmount(() => { window.removeEventListener("click", savePoint); }); return point; }
Use in components
<template> <h2>The coordinates of the mouse when clicking are: x: {{point.x}},y: {{point.y}}</h2> </template> <script> import usePoint from '../hook/point.js' export default { name:'HelloWorld', setup(){ const point = usePoint() return {point} } } </script>
7, toRef and toRefs
- Function: create a ref object whose value points to an attribute in another object.
- Syntax: const name = toRef(person, 'name')
- Application: when you want to provide a property in a responsive object to external users separately.
- Extension: the function of toRefs is the same as that of toRef, but multiple ref objects can be created in batch. Syntax: toRefs(person)
<template> <h4>{{person}}</h4> <h2>full name:{{name}}</h2> <h2>Age:{{age}}</h2> <h2>Salary:{{job.j1.salary}}K</h2> <button @click="name+='~'">Modify name</button> <button @click="age++">Growing age</button> <button @click="job.j1.salary++">Pay rise</button> </template> <script> import {ref,reactive,toRef,toRefs} from 'vue' export default { name: 'HelloWorld', setup(){ let person = reactive({ name:'Zhang San', age:18, job:{ j1:{ salary:20 } } }) // const name1 = person.name // console.log('%%%',name1) // const name2 = toRef(person,'name') // console.log('####',name2) const x = toRefs(person) console.log('******',x) return { person, // name:toRef(person,'name'), // age:toRef(person,'age'), // salary:toRef(person.job.j1,'salary'), ...toRefs(person) } } } </script>
8, Other new features
1. shallowReactive and shallowRef
- shallowReactive: deals only with the response of the outermost attribute of the object (shallow response).
- shallowRef: only the response of basic data type is processed, and the response of object is not processed.
- When will it be used?
1. If there is an object data, the structure is relatively deep, but the change is only the outer attribute change = = = > shallowreactive.
2. If there is an object data, the subsequent function will not modify the attributes in the object, but generate a new object to replace = = = > shallowref.
2. readonly and shallowReadonly
- readonly: make a responsive data read-only (deep read-only).
- shallowReadonly: make a responsive data read-only (shallow read-only).
- Application scenario: when you do not want the data to be modified.
3. toRaw and markRaw
toRaw
Function: convert a responsive object generated by reactive into a normal object.
Usage scenario:
- It is used to read the ordinary object corresponding to the responsive object. All operations on this ordinary object will not cause page update.
markRaw
Purpose: mark an object so that it will never become a responsive object again.
Application scenario:
- Some values should not be set to be responsive, such as complex third-party class libraries.
- Skipping reactive conversions can improve performance when rendering large lists with immutable data sources
4,customRef
Function: create a custom ref and explicitly control its dependency tracking and update trigger.
Achieve anti shake effect
<template> <input type="text" v-model="keyWord" /> <h3>{{ keyWord }}</h3> </template> <script> import { customRef } from "vue"; export default { name: "App", setup() { //Customize a ref -- named myRef function myRef(value, delay) { let timer; return customRef((track, trigger) => { return { get() { console.log(`Someone from myRef I read the data in this container. I put it ${value}Give it to him`); track(); // Inform Vue to track the change of value (discuss with get in advance to make him think this value is useful) return value; }, set(newValue) { console.log(`Someone put myRef The data in this container is changed to: ${newValue}`); clearTimeout(timer); timer = setTimeout(() => { value = newValue; trigger(); // Notify Vue to re resolve the template }, delay); }, }; }); } // let keyWord = ref('hello ') / / use the ref provided by Vue let keyWord = myRef("hello", 500); //Use programmer defined ref return { keyWord }; }, }; </script>
5. provide and inject
Function: realize the communication between progeny and descendant components
Routine: the parent component has a provide option to provide data, and the descendant component has an inject option to start using these data
Specific writing method
In the parent assembly:
setup(){ ...... let car = reactive({name:'Benz',price:'40 ten thousand'}) provide('car',car) // Pass data to your descendant components ...... }
In descendant components:
setup(props,context){ ...... const car = inject('car') // Get the data of your ancestors return {car} ...... }
6. Judgment of responsive data
isRef: check whether a value is a ref object.
isReactive: checks whether an object is a responsive proxy created by reactive.
isReadonly: checks whether an object is a read-only proxy created by readonly.
isProxy: check whether an object is a proxy created by the reactive or readonly method.
9, New components
1,Fragment
In Vue2: the component must have a root label
In Vue3: components can have no root tag, and multiple tags will be included in a Fragment virtual element
Benefits: reduce tag levels and memory usage
2,Teleport
Teleport is a technology that can move our component html structure to a specified location.
3,Suspense
Render some extra content while waiting for asynchronous components, so that the application has a better user experience
Use steps:
Asynchronous import component
import {defineAsyncComponent} from 'vue' const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
Use suspend to wrap components and configure default and fallback
<template> <div class="app"> <h3>I am App assembly</h3> <Suspense> //default: the content to be displayed by the component <template v-slot:default> <Child/> </template> //fallback: the component is not fully loaded with a spare tire <template v-slot:fallback> <h3>Loading.....</h3> </template> </Suspense> </div> </template>
10, Other changes
1. The data option should always be declared as a function
2. Change of transition class name
//Vue2.x writing .v-enter, .v-leave-to { opacity: 0; } .v-leave, .v-enter-to { opacity: 1; } //Vue3.x writing .v-enter-from, .v-leave-to { opacity: 0; } .v-leave-from, .v-enter-to { opacity: 1; }
3. Remove keyCode as the modifier of v-on and no longer support config keyCodes
4. Remove v-on Native modifier
5. Remove filter
Bili Bili's Silicon Valley teaching video - Notes
Link: https://www.bilibili.com/video/BV1Zy4y1K7SH?p=158