1,setup
vue3中一個新的配置項,值為函數(shù)。組件中所用到的數(shù)據(jù),方法,生命周期,監(jiān)視屬性,計算屬性等都要配置在setup中。
setup函數(shù)的兩種返回值
? ? ? ? 1,若返回一個對象,則對象中的屬性、方法, 在模板中均可以直接使用。
? ? ? ? 2,若返回一個渲染函數(shù):則可以自定義渲染內(nèi)容。
注意點
? ? ? ? 1,盡量不要與Vue2.x配置混用
? ? ? ? 2,setup不能是一個async函數(shù),因為返回值不再是return的對象, 而是promise, 模板看不到return對象中的屬性。
? ? ? ? 3,vue3不需要最外層的div,可以直接在template里面寫
<template>
<h1>vue3</h1>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<h2>{{sex}}</h2>
<button @click="introduce">vue3入門</button>
</template>
<script>
export default{
setup(){
//數(shù)據(jù)
let name="張三"
let age=18
let sex="男"
//方法
function introduce(){
console.log(`我的名字叫${name},我今天${age}歲,我的性別是${sex}`)
}
//返回一個對象
return {
name,
age,
sex,
introduce
}
}
}
</script>
2,ref函數(shù)
作用:定義一個響應(yīng)式數(shù)據(jù)。創(chuàng)建一個包含響應(yīng)式數(shù)據(jù)的引用對象(處理對象數(shù)據(jù))。
<template>
<h1>vue3</h1>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<button @click="modify">動態(tài)數(shù)據(jù)-基本數(shù)據(jù)類型</button>
<h3>工作:{{obj.work}}</h3>
<h3>工資:{{obj.money}}</h3>
<button @click="GoToWork">動態(tài)數(shù)據(jù)-對象引用類型</button>
</template>
<script>
//需要先引入ref
import {ref} from 'vue'
export default{
setup(){
//基本數(shù)據(jù)類型
let name=ref("張三")
let age=ref(18)
//修改普通數(shù)據(jù)
function modify(){
//修改namd和age
name.value="李四"
age.value=28
}
//對象類型
let obj=ref({
work:"前端開發(fā)",
money:1000
})
function GoToWork(){
obj.value.work="測試"
obj.value.money=2000
}
//返回一個對象
return {
name,
age,
modify,
obj,
GoToWork
}
}
}
</script>
3,reactive函數(shù)
作用:定義一個對象類型的響應(yīng)式數(shù)據(jù),基本類型還是用ref
語法:const 代理對象=reactive(源對象)接收一個對象或數(shù)據(jù),返回一個代理對象Proxy的實例對象,內(nèi)部是基于ES6 Proxy來進行實現(xiàn)的,通過代碼理對象操作源對象內(nèi)部數(shù)據(jù)進行操作。
<template>
<h1>vue3</h1>
<h2>姓名:{{Obj.name}}</h2>
<h2>年紀:{{Obj.age}}</h2>
<h2>工作:{{Obj.job.work}} 我的工資是{{Obj.job.money}}</h2>
<h2>其它:{{Obj.other}}</h2>
<button @click="reactiveTest">reactive測試</button>
</template>
<script>
//要先引入reactive
import {reactive} from 'vue'
export default{
setup(){
//reactive的使用
let Obj=reactive({
name:"李四",
age:18,
job:{
work:"前端開發(fā)工程師",
money:1000
},
other:['看書','運動','打球']
})
function reactiveTest(){
Obj.name="王五"
Obj.age=28
Obj.job.work="java開發(fā)"
Obj.job.money=1200
Obj.other[2]='唱歌'
}
return {
Obj,
reactiveTest
}
}
}
</script>
4,reactive對比ref
從定義數(shù)據(jù)角度
1,ref用來定義基本類型數(shù)據(jù)(ref也可以用來定義對象或數(shù)組類型數(shù)據(jù),它內(nèi)部會自動通過reactive轉(zhuǎn)為代碼對象)
2,reactive用來定義對象或數(shù)組類型數(shù)據(jù)
從原理對比角度
1,ref是通過Object.defineProperty()的訪問器屬性get和set來實現(xiàn)響應(yīng)的
2,reactive是通過ES6中的proxy來實現(xiàn)響應(yīng),并通過Relect操作源對象內(nèi)部的數(shù)據(jù)
5,setup的兩個注意點
1,set的執(zhí)行時機:在beforeCreate之前只執(zhí)行一次,this是undefined。(setup的執(zhí)行比beforeCreate要早)
2,setup的參數(shù)(一共有兩個props和context)
? ? ? ? (1) props:值為對象,包含:組件外部傳遞過來,且組件內(nèi)部聲明接收 了的屬性。
? ? ? ? (2) context上下文對象
? ? ? ? ? ? ? ? --1-- attrs:值為對象,包含:組件外部傳遞過來,但沒有props配置中聲明的屬性,相當于this.$attrs
? ? ? ? ? ? ? ? --2-- slots:收到的插槽內(nèi)容, 相當于 this.$slots。
? ? ? ? ? ? ? ? --3-- emit:分發(fā)自定義的事件函數(shù),相當于this.$emit。
//父組件
<template>
<!-- 添加setupTest自定義事件 -->
<setupTestVue @setupTest="emitClick" name="張三" age="19">
<template v-slot:asd>
<span>哈哈哈</span>
</template>
</setupTestVue>
</template>
<script>
import setupTestVue from './components/setupTest.vue'
export default {
name: 'App',
components: {
setupTestVue
},
setup(){
function emitClick(){
console.log("觸發(fā)了事件")
}
return{
emitClick
}
}
}
</script>
//子組件
<template>
<h1>sutup的注意點</h1>
<h2>姓名:{{Obj.name}}</h2>
<h2>年紀:{{Obj.age}}</h2>
<button @click="test">測試一下觸發(fā)父組件中的事件</button>
</template>
<script>
//
import {reactive} from 'vue'
export default{
beforeCreate(){
console.log("beforeCreate")
},
//對父組件中定義的參數(shù)進行接收
props:['name','age'],
//對父組件中的事件進行接收
emits:['setupTest'],
setup(props,context){
console.log("setup",props,context.slots)
let Obj = reactive({
name:"小趙",
age:18
})
function test(){
//調(diào)用父組件中的emitClick事件
context.emit('setupTest',666)
}
return{
Obj,
test
}
}
}
</script>
6,計算屬性與監(jiān)視屬性
? ? ? ? 1,computed函數(shù),用之前需要先引用。
<template>
<h1>sutup的注意點</h1>
<input type="text" v-model="Obj.name">
<br/>
<input type="text" v-model="Obj.age">
<span>{{computerResult2}}</span>
</template>
<script>
//vue3中的計算屬性是一個組合的api,在使用之前需要先引入
import {computed, reactive} from 'vue'
export default{
beforeCreate(){
console.log("beforeCreate")
},
setup(){
let Obj = reactive({
name:"小趙",
age:18
})
//1,計算屬性簡寫形式
let computerResult1=computed(()=>{
return Obj.name+'-'+Obj.age
})
//2,計算屬性完整寫法
let computerResult2=computed({
get(){
return Obj.name+'-'+Obj.age
},
set(value){
const newResult = value.split('-')
Obj.name=newResult[0]
Obj.age=newResult[1]
}
})
return{
Obj,
computerResult1,
computerResult2
}
}
}
</script>
2,watch函數(shù)
兩種常用的監(jiān)視用法
<template>
<h1>監(jiān)視屬性的使用</h1>
<h2>累加:{{sum}}</h2>
<h2>累加:{{adds}}</h2>
<button @click="sum++">點擊</button>
<button @click="adds+='++'">修改信息</button>
</template>
<script>
//需要先引入watch
import {ref,watch} from 'vue'
export default{
setup(){
let sum = ref(0)
let adds=ref('大家好')
//1,第一種寫法,監(jiān)視一個響應(yīng)式數(shù)據(jù)
// watch(sum,(newvalue,oldvalue)=>{
// console.log('sum變民',newvalue,oldvalue)
// })
//2,監(jiān)視所定義的多個響應(yīng)式數(shù)據(jù),直接傳一個數(shù)組
watch([sum,adds],(newvalue,oldvalue)=>{
console.log(newvalue,oldvalue)
},{immediate:true})
return{
sum,
adds
}
}
}
</script>
其它的監(jiān)視寫法
let Obj=reactive({
name:"張三",
age:18,
other:{
job:"軟件開發(fā)工程師"
}
})
/*
情況三:監(jiān)視reactive所定義的一個響應(yīng)式數(shù)據(jù)的全部屬性
1.注意:此處無法正確的獲取oldValue
2.注意:強制開啟了深度監(jiān)視(deep配置無效)
*/
/* watch(Obj,(newValue,oldValue)=>{
console.log('Obj變化了',newValue,oldValue)
},{deep:false}) //此處的deep配置無效 */
//情況四:監(jiān)視reactive所定義的一個響應(yīng)式數(shù)據(jù)中的某個屬性,需要是一個函數(shù)
/* watch(()=>Obj.name,(newValue,oldValue)=>{
console.log('Obj的name變化了',newValue,oldValue)
}) */
//情況五:監(jiān)視reactive所定義的一個響應(yīng)式數(shù)據(jù)中的某些屬性,監(jiān)視多個,需要一個數(shù)組
/* watch([()=>Obj.name,()=>Obj.age],(newValue,oldValue)=>{
console.log('Obj的name或age變化了',newValue,oldValue)
}) */
//特殊情況
watch(()=>person.job,(newValue,oldValue)=>{
console.log('Obj的job變化了',newValue,oldValue)
},{deep:true}) //此處由于監(jiān)視的是reactive素定義的對象中的某個屬性,所以deep配置有效
7,watchEffect函數(shù)
watchEffect:不用指明監(jiān)視哪個屬性,監(jiān)視的回調(diào)中用到哪個屬性,那就監(jiān)視哪個屬性。
watchEffect有點像computed:
? ? ? 1,但computed注重的計算出來的值(回調(diào)函數(shù)的返回值),所以必須要寫返回值。
? ? ? 2,而watchEffect更注重的是過程(回調(diào)函數(shù)的函數(shù)體),所以不用寫返回值。
<template>
<h1>監(jiān)視屬性的使用</h1>
<h2>累加:{{sum}}</h2>
<h2>累加:{{adds}}</h2>
<button @click="sum++">點擊</button>
<button @click="adds+='++'">修改信息</button>
</template>
<script>
//需要先引入watchEffect
import {reactive, ref, watchEffect} from 'vue'
export default{
setup(){
let sum = ref(0)
let adds=ref('大家好')
//可以
watchEffect(()=>{
let val1=sum.value
let val2=adds.value
console.log(val1,val2)
console.log("被調(diào)用了")
})
return{
sum,
adds,
Obj
}
}
}
</script>
8,hooks
1,hooks就是把setup函數(shù)中使用的composition API進行封裝,和vue2中的mixin很相。
2,可以進行代碼復用,讓setup中的邏輯更清晰易懂。
具體使用
在src下新建一個hooks文件里面包含一個setup.js文件用于鼠標點擊空白處,獲取對應(yīng)的坐標
import { reactive,onMounted,onBeforeUnmount } from "vue"
export default function(){
let point=reactive({
x:0,
y:0
})
//封裝一個公用方法
function savePoint(event){
point.x=event.pageX
point.y=event.pageY
console.log(event.pageX,event.pageY)
}
onMounted(()=>{
// window.addEventListener('click',(event)=>{
// point.x=event.pageX
// point.y=event.pageY
// console.log(event.pageX,event.pageY)
// })
window.addEventListener('click',savePoint)
})
onBeforeUnmount(()=>{
window.removeEventListener('click',savePoint)
})
return point
}
在其它頁面中的使用
<template>
<h1>hook的使用</h1>
<h2>累加:{{sum}}</h2>
<button @click="sum++">點擊</button>
<h2>獲取當前的鼠標坐標,x:{{point.x}}坐標點y{{point.y}}</h2>
</template>
<script>
import {ref} from 'vue'
import usePoint from '../hooks/setPoint'
export default{
setup(){
let sum = ref(0)
let point = usePoint()
console.log(point)
return{
sum,
point
}
}
}
</script>
9,toRef和toRefs
1,toRef創(chuàng)建一個ref對象,其value值指向另一個對象中的某個屬性
2,語法const name=toRef(Obj,"name")
3,要將響應(yīng)式對象中的某個屬性單獨提供給外部使用
<template>
<h1>toRef的使用</h1>
<h2>姓名:{{name}}</h2>
<h2>年紀:{{age}}</h2>
<h2>年紀:{{money}}</h2>
</template>
<script>
//引入toRef
import {toRef} from 'vue'
export default{
setup(){
let Obj={
name:"張三",
age:18,
job:{
eng:{
money:30
}
}
}
return{
//Obj,
name:toRef(Obj,'name'),
age:toRef(Obj,'age'),
money:toRef(Obj.job.eng,'money')
}
}
}
</script>
4,toRefs與toRef的功能一樣,但可以批量創(chuàng)建多個ref對象
<template>
<h1>toRef的使用</h1>
<h2>姓名:{{name}}</h2>
<h2>年紀:{{age}}</h2>
<h2>年紀:{{job.eng.money}}</h2>
</template>
<script>
//引入toRefs
import {toRefs} from 'vue'
export default{
setup(){
let Obj={
name:"張三",
age:18,
job:{
eng:{
money:30
}
}
}
return{
...toRefs(Obj)
}
}
}
</script>
10,其它Composition API
????????一,shallowReactive與shallowRef
????????????????1,shallowReactive:只處理對象最外層的響應(yīng)式(只處理一層)
????????????????2,shallowRef:只處理基本數(shù)據(jù)類型的響應(yīng)式,不進行對象的響應(yīng)式處理
????????什么時候使用
? ? ? ? ? ? ? ? 什么時候使用?
? ? ? ? ? ? ? ? A:如果有一個對象數(shù)據(jù),結(jié)構(gòu)比較深,但變化時只是最外層的屬性變化就用 shallowReactive
? ? ? ? ? ? ? ? B:如果有一個對象數(shù)據(jù),后續(xù)功能不會修改該對象中的屬性,而是新的對象來替換就使用shallowRef
shallowReactive的使用
<template>
<h1>shallowReactive的使用</h1>
<h2>姓名:{{name}}</h2>
<h2>年紀:{{age}}</h2>
<h2>年紀:{{job.eng.money}}</h2>
<button @click="age++">修改年紀</button>
</template>
<script>
//引入toRefs
import {toRefs,shallowReactive} from 'vue'
export default{
setup(){
//job里面的數(shù)據(jù)不會受到影響
let Obj=shallowReactive({
name:"張三",
age:18,
job:{
eng:{
money:30
}
}
})
return{
...toRefs(Obj)
}
}
}
</script>
二,readonly與shallowReadonly
? ? ? ? readonly:讓一個響應(yīng)式數(shù)據(jù)變?yōu)橹弊x的(深度)
? ? ? ? shallowReadonly:讓一個響應(yīng)式數(shù)據(jù)變?yōu)橹蛔x的(只讀一層)
? ? ? ? 應(yīng)用場景,不希望數(shù)據(jù)被修改
<template>
<h1>shallowReactive的使用</h1>
<h2>姓名:{{name}}</h2>
<h2>年紀:{{age}}</h2>
<h2>年紀:{{job.eng.money}}</h2>
<button @click="age++">修改年紀</button>
<button @click="job.eng.money++">修改薪水</button>
</template>
<script>
//引入toRefs
import {toRefs,reactive,readonly,shallowReadonly} from 'vue'
export default{
setup(){
let Obj=reactive({
name:"張三",
age:18,
job:{
eng:{
money:30
}
}
})
//禁止響應(yīng)式的數(shù)據(jù)進行修改全部
//Obj=readonly(Obj)
//只限制第一層的數(shù)據(jù)只讀
Obj=shallowReadonly(Obj)
return{
...toRefs(Obj)
}
}
}
</script>
三,toRaw與markRaw
toRaw
? ? ? ? 作用:將一個由reactive生成的響應(yīng)式對象轉(zhuǎn)為普通對象
? ? ? ? 使用場景:用于讀取響應(yīng)式對象中的普通對象,這個普通對象的所有操作,不會引起頁面更新
<template>
<h1>toRaw的使用</h1>
<h2>姓名:{{name}}</h2>
<h2>年紀:{{age}}</h2>
<h2>年紀:{{job.eng.money}}</h2>
<button @click="showToRaw">輸出最原始的Obj</button>
</template>
<script>
//引入toRaw
import {toRefs,reactive,toRaw} from 'vue'
export default{
setup(){
let Obj=reactive({
name:"張三",
age:18,
job:{
eng:{
money:30
}
}
})
function showToRaw(){
let O = toRaw(Obj)
O.age++
console.log(O)//輸出的結(jié)果為一個普通對象
}
return{
...toRefs(Obj),
showToRaw
}
}
}
</script>
markRaw
? ? ? ? 作用:標記一個對象,使用其不會成為響應(yīng)式對象
? ? ? ? 應(yīng)用場景:
? ? ? ? ? ? ? ? 1,有些值不應(yīng)該被設(shè)置為響應(yīng)式的,例如復雜的第三方庫等
? ? ? ? ? ? ? ? 2,當渲染具有不可變數(shù)據(jù)源的大列表時,跳過響應(yīng)式轉(zhuǎn)換可以提高性能
<template>
<h1>markRaw的使用</h1>
<h2>姓名:{{name}}</h2>
<h2>年紀:{{age}}</h2>
<h2>年紀:{{job.eng.money}}</h2>
<button @click="showMarkRaw">輸出最原始的Obj</button>
</template>
<script>
//引入markRaw
import {toRefs,reactive,markRaw} from 'vue'
export default{
setup(){
let Obj=reactive({
name:"張三",
age:18,
job:{
eng:{
money:30
}
}
})
function showMarkRaw(){
let others={address:"湖北武漢",weight:180}
Obj.others=markRaw(others)
console.log(Obj)
}
return{
...toRefs(Obj),
showMarkRaw,
}
}
}
</script>
? ?四,customRef
? ? ? ? 作用:創(chuàng)建一個自定義的ref,并對其依賴項跟蹤和更新觸發(fā)進行顯示控制。
<template>
<input type="text" v-model="keyWord">
<h3>{{keyWord}}</h3>
</template>
<script>
import {ref,customRef} from 'vue'
export default {
name: 'App',
setup() {
//自定義一個ref——名為:myRef
function myRef(value,delay){
let timer
//需要接受的兩個參數(shù)track,trigger
return customRef((track,trigger)=>{
return {
get(){
console.log(`有人從myRef這個容器中讀取數(shù)據(jù)了,我把${value}給他了`)
track() //通知Vue追蹤value的變化(提前和get商量一下,讓他認為這個value是有用的)
return value
},
set(newValue){
console.log(`有人把myRef這個容器中數(shù)據(jù)改為了:${newValue}`)
clearTimeout(timer)
timer = setTimeout(()=>{
value = newValue
trigger() //通知Vue去重新解析模板
},delay)
},
}
})
}
// let keyWord = ref('hello') //使用Vue提供的ref
let keyWord = myRef('hello',500) //使用程序員自定義的ref
return {keyWord}
}
}
</script>
五,provide和inject
作用:實現(xiàn)祖與后代組件之間的通信
用法:父組件有一個provide選擇來提供數(shù)據(jù),后代組件有一個inject選項來開始使用這些數(shù)據(jù)
//祖祖組件
<template>
<!-- 我是祖祖組件 -->
<div>
<h3>我是App組件</h3>
<h3>{{name}}--{{price}}</h3>
<ChildsVue/>
</div>
</template>
<script>
//引入provide
import {reactive,toRefs,provide} from 'vue'
import ChildsVue from './components/ChildView.vue'
export default {
name: 'App',
components: {
ChildsVue
},
setup(){
//將祖祖組件的內(nèi)容傳遞到孫組件
let car = reactive({
name:"三輪車",
price:"3000元"
})
provide('car',car)//給自己的后代元素傳遞數(shù)據(jù)
return{
...toRefs(car)
}
}
}
</script>
//父組件
//子組件里面也可以使用inject
<template>
<div class="Childs">
<h1>子組件</h1>
<sonVue/>
</div>
</template>
<script>
import sonVue from './sonView.vue'
export default{
name:"ChildView",
components:{sonVue}
}
</script>
<style>
.Childs{
background-color: gray;
padding: 10px;
}
</style>
//孫子組件
<template>
<div class="son">
<h1>孫組件</h1>
</div>
</template>
<script>
// 在孫子組件里面進行接受
import {inject} from 'vue'
export default{
name:"sonView",
setup(){
let car = inject('car')
console.log(car,'+++++')
}
}
</script>
<style>
.son{
background-color: gold;
padding: 10px;
}
</style>
六,響應(yīng)式數(shù)據(jù)的判斷
isRef:檢查一個值是否為一個ref對象
isReactive:檢查一個對象是否由reactive創(chuàng)建的響應(yīng)式代理
isReadonly:檢查一個對象是否由readonly創(chuàng)建的只讀對象
isProxy:檢查一個對象是否由react或者readonly方法創(chuàng)建的代理對象
<template>
<h3>進行響應(yīng)式代理的測試</h3>
</template>
<script>
import {ref,reactive,toRefs,readonly,isRef,isReactive,isReadonly,isProxy } from 'vue'
export default {
name:'App',
setup(){
let car = reactive({name:'三輪車',price:'3000元'})
let sum = ref(0)
let car2 = readonly(car)
console.log(isRef(sum))//true
console.log(isReactive(car))//true
console.log(isReadonly(car2))//true
console.log(isProxy(car))//true
console.log(isProxy(sum))//false
return {...toRefs(car)}
}
}
</script>
<style>
.app{
background-color: gray;
padding: 10px;
}
</style>
11,Teleport
? ? ? ? teleport是一種能夠?qū)⑽覀兊慕M件html結(jié)構(gòu)移動到指定位置的技術(shù)
? ? ? ? 例如父組件里面包含子組件,子組件是一個彈窗,需要把彈窗移動給body
????????
//父組件
<template>
<div class="son">
<h1>父組件</h1>
<DialogVue/>
</div>
</template>
<script>
// 父組件里面包括子組件
import DialogVue from './DialogView.vue'
export default{
name:"sonView",
components:{DialogVue},
}
</script>
<style>
.son{
background-color: gold;
padding: 10px;
}
</style>
//子組件,要移動的組件
<template>
<div>
<button @click="isShow=true">彈窗</button>
<!--這里的to可以是html,body或者是某個指定的選擇器,如果是選擇器前面需要加#號-->
<teleport to="body">
<div v-if="isShow" class="DialogView">
<h1>這是一個對話彈</h1>
<h4>描述</h4>
<button @click="isShow=false">關(guān)閉</button>
</div>
</teleport>
</div>
</template>
<script>
import {ref} from 'vue'
export default {
name:"DialogView",
setup(){
let isShow = ref(false)
return{
isShow
}
}
}
</script>
<style>
.DialogView{
width:300px;
height: 300px;
background-color: aqua;
}
</style>
12,Susperse
等待異步組件渲染時做一些其它的事情
使用步驟
1,引入異步組件文章來源:http://www.zghlxwxcb.cn/news/detail-823784.html
2,使用Susperse包裹好組件,并配置好default與fallback文章來源地址http://www.zghlxwxcb.cn/news/detail-823784.html
<template>
<div class="Childs">
<h1>父組件</h1>
<Suspense>
<template v-slot:default>
<sonVue/>
</template>
<template v-slot:fallback>
<h3>正在加載中.....</h3>
</template>
</Suspense>
</div>
</template>
<script>
//靜態(tài)引入
//import sonVue from './sonView.vue'
//異步引入或者叫動態(tài)引入
import {defineAsyncComponent} from 'vue'
const sonVue = defineAsyncComponent(()=>import('./sonView.vue'))
export default{
name:"ChildView",
components:{sonVue}
}
</script>
<style>
.Childs{
background-color: gray;
padding: 10px;
}
</style>
到了這里,關(guān)于vue3常用知識點梳理的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!