Preparation before creating a project
Verify that vUE scaffolding is installed before creating the project
Erection of scaffolding
npm install -g @vue/cli
Copy the code
The Vue CLI3 version is installed above
Create a project
Vue create Project nameCopy the code
Create a step
Node version 10.0 or later
Notable new Vue3 features
Composition API
What problem does composition-API solve
The problem of using the traditional option configuration method to write components is that with the increasing business complexity, the amount of code will continue to increase. As the codes of related businesses need to be written to specific areas according to the configuration of Option, subsequent maintenance is very complicated and the code reusability is not high. Comcomposition API is born to solve this problem.
The Composition API needs to be introduced before you use it
import { reactive, toRefs, computed } from "vue";
Copy the code
Setup is the entry function to composition-API 2. Called before the cycle beforeCreate event is declared; 3. Can return an object whose properties are merged into the render context and can be used directly in the template; As the first parameter, the props object is received, which can be monitored by watchEffect. Take the context object as the second argument. This object contains the attrs, slots, and emit attributes. 4. Context replaces this
Because setup is executed before the component sample is created, there is no this in setup. This means that you cannot use any properties defined within the component other than props, including local state, computed properties, and methods.
setup(props, ctx) {
ctx.emit('and' transfer}}}}}}}}}setup(props, { emit }) {
emit('ooxx')}Copy the code
Introduction to Grammar sugar
The Compositon-API provides the following functions
- ref
- reactive
- toRefs
- computed
- watch
- watchEffect
- Hooks for the lifecycle
ref
Accepts a parameter value and returns a reactive and mutable REF object
- The ref object has a single.value attribute that points to an internal value
- When ref is used in a template, it is unwrapped automatically, without the need to write an extra.value inside the template
import { reactive, toRefs, computed } from "vue";
export default {
const count = ref(0)
const countAdd = () = >{
count.value ++
}
return {
count
countAdd
}
}
Copy the code
reactive
Receives a normal object and returns the normal queue of reactive proxies, equivalent to the ue. Observable () of 2.x. Reactive transformations are “deep” : they affect all nested properties inside the object
import { reactive, toRefs, computed } from "vue";
export default {
const state = reactive({ count: 0.double: computed(() = >state.count * 2)})return{... toRefs(state) double } }Copy the code
import { reactive, toRefs, computed } from "vue";
export default {
const state = reactive({ count: 0.double: computed(() = >state.count * 2)})return toRefs(state)
}
Copy the code
reactive
andref
To choose between
Both are used to turn normal data into responsive data
When a reactive data object created by ref() is mounted to reactive(), the reactive data object is automatically expanded to its original value, and can be accessed directly without.value. The new ref will overwrite the original ref value, but ref and state are independent of each other, and the change of state.ref value will not affect the ref value, so the new ref overwrites the old ref, covering only the pointer to the data. Ref is used for simple data types, and Reactive is used for complex data types. 4. Ref does not need to be deconstructed when it returns, and state needs to be deconstructed when it returns. Reactive is used for highly relevant data, so that the code is more complete and clean
toRefs
1. The toRefs API provides a way to process reactive to ref 2. Turn reactive data objects created by Reactive into normal objects, except that each attribute node of the normal object is reactive data of type REF. The extended operator is used to convert state to normal, so it needs toRefs to convert it to reactive data.
import { reactive, toRefs, computed } from "vue";
export default {
setup() {
const state = reactive({ count: 0 })
const increment = () = > { // Define the event handlers available on the page
state.count++
}
// This return object can contain either responsive data or event handlers
return {
...toRefs(state),
increment
}
}
}
Copy the code
Computed()
- Create the evaluated property, and the return value is a ref instance, so there is also a.value property
- Import it before use
- Create a read-only compute property:
export default {
setup(props, context) {
const tempData = ref(0);
const computeData = computed(() = > {
tempData.value += 1; // The returned computeData is also of type REF
})
console.log(tempData.value) / / 0
console.log(computeData.value) / / 1}}Copy the code
- Create computable properties that are readable and writable:
export default {
setup(props, context) {
const tempData = ref(0);
const computeData = computed({
get: () = > {
tempData.value += 1;
},
set: (val) = > {
tempData.value = val - 1; }})console.log(tempData.value) / / 0
console.log(computeData.value) / / 1
computeData.value = 9;
console.log(tempData.value) / / 8}}Copy the code
watch(arg1,arg2,arg3)
- Monitoring data changes, automatically called once when created, can be turned off with the third parameter of watch {lazy: true}. The third parameter is used to configure listening parameters, such as immediately
- First entry required
- Single data listener:
export default {
setup(prop, context) {
/ / ref type
const tempData = ref(0)
watch(
tempData,
(newVal, oldVal) = > {
console.log(newVal);
},
{
lazy: true})/ / reactive type
const tempData1 =reactive({count: 0})
watch(
() = >tempData1.count,
(newVal, oldVal) = > {
console.log(newVal);
},
{
lazy: true}}})Copy the code
- Listen for multiple data changes
export default {
setup() {
/ / ref type
const count = ref(0)
const name = ref('jack')
watch(
[count, name],
([newcount, newname], [oldcount, oldname]) = > {
console.log(newcount, oldcount);
},
{
lazy: true})setTimeout(() = > {
count.value++
name.value = 'lc'
}, 1000)
/ / reactive type
const state = reactive({
count: 0.name : 'jack'
})
watch(
[() = >state.count, () = >state.name], // Listen to the data group
([newcount, newname], [oldcount, oldname]) = > { // The callback function
console.log(newVal);
},
{
lazy: true})setTimeout(() = > {
state.count++
state.name = 'lc'
}, 1000)}}Copy the code
- Cleared to monitor
// Call the return value of watch.
const stop = watch(...)
stop() // Clear the listener
Copy the code
- Clear invalid asynchronous tasks
The cleanup function is called when:
Watch is repeated
Watch was forced to stop
export default {
setup() {
const count = ref(0)
// declare a listener
const stop = watch(
count,
(newVal, oldVal, onClear) = > {
const timeId = asyncPrint(newVal) // Call the asynchronous method
onClear(() = > { // Repeat listener deletes previous operations
clearTimeout(timeId)
})
},
{lazy: true})// Asynchronous method
const asyncPrint = (val) = > {
return setTimeout(() = > {
console.log(val)
},3000)}}}Copy the code
watchEffect
WatchEffect collects dependencies from the beginning. Unlike watch, which controls whether to listen immediately upon initialization, watchEffect must be executed once at the beginning to collect dependencies. Therefore, watchEffect does not have a first parameter to specify dependencies like watch. If ref1 is changed outside, console.log(ref2) has no effect, but watch does
import { watchEffect } from 'vue'
const state1 = reactive({name: 'jack'})
setTimeout(() = > {
state1.name = 'lc'
},8000)
watchEffect(() = > {
console.log(state1.name) // Can not listen
})
Copy the code
- In Vue3.0, if watch is an array object, then the push method will not trigger the listening, and the array must be reassigned to trigger the listening.
provide
- Data can be passed between nested components, with the provide() function being used in parent components to pass data to child components
- There is no hierarchy, as long as it is a nested child component
- Used in setup()
- We need to introduce
- Sharing Common Data
export default {
setup() {
provide('globalColor'.'red')}}Copy the code
- Share ref responsive data
export default {
setup() {
const color = ref('red')
provide('globalColor', color)
}
}
Copy the code
inject
- Data transfer between nested components can be realized. Inject () function is used in child components to receive data from parent components
- There’s no hierarchy, as long as it’s its parent,
- Used in setup()
- We need to introduce
- Receives the parameter from the parent
export default {
setup() {
inject('globalColor')}}Copy the code
The template – refs
- Ref () is used to reference and manipulate page DOM elements and components
- The parent component can manipulate the child component and get its data
- The instance
<template>
<h3 ref='h3ref'><h3/>// Bind the response object data for return<com-child ref='comChild'/>
<template/>
<script>
export default {
setup() {
const h3ref = ref(null) // define ref with the value null
const comChild = ref(null)
onMounted(() = >{
// h3ref.value is equivalent to a native DOM
h3ref.value.style.color = 'red'
})
// Get the DOM of the child component
const showNumber = () = > {
console.log(comChild.value.count)
}
return {
h3ref,
comChild,
showNumber
}
}
}
</script>
Copy the code
The life cycle
The life cycle is written in setup()
Import should be introduced in advance
import { onBeforeMount, onMounted, reactive, watchEffect } from 'vue'
Copy the code
Comparison of old and new life cycles:
BeforeCreate -- setup() created -- setup() beforeMount -- onBeforeMount(()=>{... }) mounted - onMounted (() = > {... }) beforeUpdate - onBeforeUpdate (() = > {... }) updated - onUpdated (() = > {... }) beforeDestroy - onBeforeUnmount (() = > {... }) destroyed - onUnmounted (() = > {... }) errorCaptured - onErrorCaptured (() = > {... })Copy the code