1.Vue簡介
2020年9月18日,Vue.js
發布版3.0
版本,代號:One Piece
1.1.
性能的提升
????????打包大小減少41%
。
????????初次渲染快55%
, 更新渲染快133%
。
????????內存減少54%
。
1.2.
源碼的升級
????????使用Proxy
代替defineProperty
實現響應式。
?????????重寫虛擬DOM
的實現和Tree-Shaking
。
1.3.
擁抱TypeScript
? Vue3
可以更好的支持TypeScript
。
1.4 新的特性
? ? ? ? ref和reactive
? ? ? ? 新的生命周期函數
2.創建Vue3工程
基于 vite 創建(推薦)
## 1.創建命令
npm create vue@latest## 2.具體配置
## 配置項目名稱
√ Project name: vue3_test
## 是否添加TypeScript支持
√ Add TypeScript? Yes
## 是否添加JSX支持
√ Add JSX Support? No
## 是否添加路由環境
√ Add Vue Router for Single Page Application development? No
## 是否添加pinia環境
√ Add Pinia for state management? No
## 是否添加單元測試
√ Add Vitest for Unit Testing? No
## 是否添加端到端測試方案
√ Add an End-to-End Testing Solution? ? No
## 是否添加ESLint語法檢查
√ Add ESLint for code quality? Yes
## 是否添加Prettiert代碼格式化
√ Add Prettier for code formatting? No
3.Vue3核心語法
3.1.OptionsAPI 與 CompositionAPI
? ? ? ? Vue2的APi設計是Options(配置)風格,Vue3則是Composition(組合)風格,讓相關功能的代碼更加有序的組合在一起
3.2.setup
概述
注意:setup函數中訪問this是undefined
? ? ? ? ? ?所有值和函數都可以定義到setup函數中,但需要通過return“交出去”出來讓外界使用
<template><div class="person"><h2>姓名:{{name}}</h2><h2>年齡:{{age}}</h2><button @click="changeName">修改名字</button><button @click="changeAge">年齡+1</button><button @click="showTel">點我查看聯系方式</button></div>
</template><script lang="ts">export default {name:'Person',setup(){// 數據,原來寫在data中(注意:此時的name、age、tel數據都不是響應式數據)let name = '張三'let age = 18let tel = '13888888888'// 方法,原來寫在methods中function changeName(){name = 'zhang-san' //注意:此時這么修改name頁面是不變化的console.log(name)}function changeAge(){age += 1 //注意:此時這么修改age頁面是不變化的console.log(age)}function showTel(){alert(tel)}// 返回一個對象,對象中的內容,模板中可以直接使用return {name,age,tel,changeName,changeAge,showTel}}}
</script>
?setup返回值
如果時返回一個對象則正常被調用
如果返回是一個函數,則會自動掛載,無關模板
setup(){return ()=> '你好啊!'
}
setup語法糖
?一般來說需要使用vite插件簡化
step1:npm i vite-plugin-vue-setup-extend -D
step2:修改vite.config.ts
import { defineConfig } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'export default defineConfig({plugins: [ VueSetupExtend() ]
})
step3:直接<script setup lang="ts" name="Person">
3.3.ref 創建:基本類型的響應式數據
import {ref} from 'vue'
語法:let age = ref(初始值),
返回值:是RefImpl的實例對象,簡稱ref對象,ref對象的value屬性是響應式的
注意
? ? ? ? 1.js中操作響應式對象需要用 xx.value ,在模板中直接用即可,無需.value
? ? ? ? 2.對于 let age = ref(18)來說,age不是響應式的,age.value是響應式的
3.4.reactive 創建:對象類型的響應式數據
import { reactive } from 'vue'
語法:iet 響應式對象 = reactive(源對象)
返回值:proxy的實例對象,簡稱響應式對象
注意.reactive不能定義基本數據類型
3.5.ref 創建:對象類型的響應式數據
若ref
接收的是對象類型,內部其實也是調用了reactive
函數。
注意:調用對象的屬性應該是? ? xx.value.屬性
代碼能證明一切
<template><div class="person"><h2>汽車信息:一臺{{ car.brand }}汽車,價值{{ car.price }}萬</h2><h2>游戲列表:</h2><ul><li v-for="g in games" :key="g.id">{{ g.name }}</li></ul><h2>測試:{{obj.a.b.c.d}}</h2><button @click="changeCarPrice">修改汽車價格</button><button @click="changeFirstGame">修改第一游戲</button><button @click="test">測試</button></div>
</template><script lang="ts" setup name="Person">
import { ref } from 'vue'// 數據
let car = ref({ brand: '奔馳', price: 100 })
let games = ref([{ id: 'ahsgdyfa01', name: '英雄聯盟' },{ id: 'ahsgdyfa02', name: '王者榮耀' },{ id: 'ahsgdyfa03', name: '原神' }
])console.log(car)function changeCarPrice() {car.value.price += 10
}
function changeFirstGame() {games.value[0].name = '流星蝴蝶劍'
}
function test(){obj.value.a.b.c.d = 999
}
</script>
3.6.ref 對比 reactive
使用原則:
- 若需要一個基本類型的響應式數據,必須使用
ref
。 - 若需要一個響應式對象,層級不深,
ref
、reactive
都可以。 - 若需要一個響應式對象,且層級較深,推薦使用
reactive
。
注意:reactive
重新分配一個新對象,會失去響應式(可以使用Object.assign
去整體替換)
let stu = reactive({name:'張三',age:18})stu = {name:'王五',age:19}//這樣會失去響應式,//可以使用Object.assign整體替換
Object.assign(stu,{'王五' ,19})
3.7 toRefs 與 toRef
作用:將一個響應式對象中的所有屬性轉化為ref對象
注意:toRefs
與toRef
功能一致,但toRefs
可以批量轉換。
<template><div class="person"><h2>姓名:{{person.name}}</h2><h2>年齡:{{person.age}}</h2><h2>性別:{{person.gender}}</h2><button @click="changeName">修改名字</button><button @click="changeAge">修改年齡</button><button @click="changeGender">修改性別</button></div>
</template><script lang="ts" setup name="Person">import {ref,reactive,toRefs,toRef} from 'vue'// 數據let person = reactive({name:'張三', age:18, gender:'男'})// 通過toRefs將person對象中的n個屬性批量取出,且依然保持響應式的能力let {name,gender} = toRefs(person)// 通過toRef將person對象中的gender屬性取出,且依然保持響應式的能力let age = toRef(person,'age')// 方法function changeName(){name.value += '~'}function changeAge(){age.value += 1}function changeGender(){gender.value = '女'}
</script>
3.8.computed
只有待計算的值發生改變,computed才可以重新計算一次(比較聰明)
默認計算的值是只讀的,只有當寫上get()和set()方法,計算出來的值才是可讀可寫的
<script setup lang="ts" name="App">import {ref,computed} from 'vue'let firstName = ref('zhang')let lastName = ref('san')// 計算屬性——只讀取,不修改/* let fullName = computed(()=>{return firstName.value + '-' + lastName.value}) */// 計算屬性——既讀取又修改let fullName = computed({// 讀取get(){return firstName.value + '-' + lastName.value},// 修改set(val){console.log('有人修改了fullName',val)firstName.value = val.split('-')[0]lastName.value = val.split('-')[1]}})//因為前面有了set方法,所以現在可讀可寫fullName.vaule = 'li-si'</script>
3.9. watch
情況一:監視ref定義的基本類型數據
監視函數watch中直接寫基本類型,無需加 ‘.value’
<template><div class="watch"><h1>{{sum}}</h1><button @click="changeSum">加一</button></div>
</template><script lang="ts" setup name="watch">
import{ref,watch} from 'vue'let sum = ref(0)
function changeSum(){sum.value+=1
}
//直接監視watch(sum,(newValue,oldValue)=>{console.log('變化了')
})
//有返回值,返回值是一個結束監視函數const stopWatch = watch(sum ,(newValue,oldValue)=>{if(sum.value>10){stopWatch()}
})</script>
情況2: 監視ref定義的對象類型數據
默認當對象的某一個屬性變化時,不會觸發監視函數回調,只有當整個對象變化(地址值變化)才會響應,但是可以開啟深度監視
/* 監視,情況一:監視【ref】定義的【對象類型】數據,監視的是對象的地址值,若想監視對象內部屬性的變化,需要手動開啟深度監視watch的第一個參數是:被監視的數據watch的第二個參數是:監視的回調watch的第三個參數是:配置對象(deep、immediate等等.....) */watch(person,(newValue,oldValue)=>{console.log('person變化了',newValue,oldValue)},{deep:true})
情況3:監視reactive定義的對象類型數據
? ? ? ? 和情況2類似,但是默認開啟深度監視
情況4:監視ref和reactive定義的對象類型中的某個屬性
1.若該屬性不是對象類型,需要寫成函數形式
2.是對象類型,可以直接寫
// 監視,情況四:監視響應式對象中的某個屬性,且該屬性是基本類型的,要寫成函數式watch(()=> person.name,(newValue,oldValue)=>{console.log('person.name變化了',newValue,oldValue)}) // 監視,情況四:監視響應式對象中的某個屬性,且該屬性是對象類型的,可以直接寫,也能寫函數,更推薦寫函數watch(()=>person.car,(newValue,oldValue)=>{console.log('person.car變化了',newValue,oldValue)},{deep:true})
情況5:監視多個屬性
// 監視,情況五:監視上述的多個數據watch([()=>person.name,person.car],(newValue,oldValue)=>{console.log('person.car變化了',newValue,oldValue)},{deep:true})
3.10.?watchEffect
不用指明監視的屬性,函數用到哪個監視哪個
const stopWtach = watchEffect(()=>{// 室溫達到50℃,或水位達到20cm,立刻聯系服務器if(temp.value >= 50 || height.value >= 20){console.log(document.getElementById('demo')?.innerText)console.log('聯系服務器')}// 水溫達到100,或水位達到50,取消監視if(temp.value === 100 || height.value === 50){console.log('清理了')stopWtach()}})
3.11.標簽的ref屬性
不同組件的即使有相同的ref也不會沖突
定位到組件上,如果想要取消保護機制,暴露屬性可以用defineExpose
<!-- 子組件Person.vue中要使用defineExpose暴露內容 -->
<script lang="ts" setup name="Person">import {ref,defineExpose} from 'vue'// 數據let name = ref('張三')let age = ref(18)/****************************//****************************/// 使用defineExpose將組件中的數據交給外部defineExpose({name,age})
</script>
補充:接口定義和使用
定義
// 定義一個接口,限制每個Person對象的格式
export interface PersonInter {id:string,name:string,age:number}// 定義一個自定義類型Persons
export type Persons = Array<PersonInter>
?使用
import {type PersonInter} from './types'import {type Persons} from './types'let person:PersonInter = {id:'asyud7asfd01',name:張三',age:60}let personList:Array<PersonInter> = [{id:'asyud7asfd01',name:'張三',age:60},{id:'asyud7asfd02',name:"李四',age:18},{id: asyud7asfd03',name:'王五',age:5}]let persons = reactive<Persons>([{id:'e98219e12',name:'張三',age:18},{id:'e98219e13',name:'李四',age:19},{id:'e98219e14',name:'王五',age:20}])
3.12.?props
讓父組件能夠向子組件傳遞數據。
<h2 a="1+1" :b="1+1" c="x"? :d="x"? ref="qwe"></h2>
<template>
<div class="person"><ul><li v-for="item in list" :key="item.id">{{item.name}}--{{item.age}}</li></ul></div></template><script lang="ts" setup name="Person">
import {defineProps} from 'vue'
import {type PersonInter} from '@/types'// 第一種寫法:僅接收const props = defineProps(['list'])// 第二種寫法:接收+限制類型const props = defineProps<{list:Persons}>()// 第三種寫法:接收+限制類型+指定默認值+限制必要性let props = withDefaults(defineProps<{list?:Persons}>(),{list:()=>[{id:'asdasg01',name:'小豬佩奇',age:18}]})console.log(props)</script>
3.12.生命周期?
注意:使用時候需要從vue中impoort
創建階段:setup
掛載階段:onBeforeMount
、onMounted
更新階段:onBeforeUpdate
、onUpdated
卸載階段:onBeforeUnmount
、onUnmounted
3.13.自定義hook
?可以在src下創建hooks文件夾存放hook文件,命名一般為“useXxx",把具有聯系的值和函數存放到一個文件夾
? ? ? ? ?例如
useSum.ts
import {ref,onMounted} from 'vue'export default function(){let sum = ref(0)const increment = ()=>{sum.value += 1}const decrement = ()=>{sum.value -= 1}onMounted(()=>{increment()})//向外部暴露數據return {sum,increment,decrement}
}
?useDog.ts
import {reactive,onMounted} from 'vue'
import axios,{AxiosError} from 'axios'export default function(){let dogList = reactive<string[]>([])// 方法async function getDog(){try {// 發請求let {data} = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')// 維護數據dogList.push(data.message)} catch (error) {// 處理錯誤const err = <AxiosError>errorconsole.log(err.message)}}// 掛載鉤子onMounted(()=>{getDog()})//向外部暴露數據return {dogList,getDog}
}
具體使用
<template><h2>當前求和為:{{sum}}</h2><button @click="increment">點我+1</button><button @click="decrement">點我-1</button><hr><img v-for="(u,index) in dogList.urlList" :key="index" :src="(u as string)"> <span v-show="dogList.isLoading">加載中......</span><br><button @click="getDog">再來一只狗</button>
</template><script setup lang="ts">import useSum from './hooks/useSum'import useDog from './hooks/useDog'let {sum,increment,decrement} = useSum()let {dogList,getDog} = useDog()
</script>
4.路由?
4.1.配置
router文件下配置
import {createRouter,createWebHistory} from "vue-router"
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'const router = createRouter({history:createWebHistory(),routes:[{path:'/home'component:Home},{}
]
})
main.ts文件
import router from './router/index'
app.use(router)app.mount('#app')
App.vue文件
注意<RouterLink to=' '></RouterLink>?和<RouterView><RouterView>
路由組件通常存放在
pages
?或?views
文件夾,一般組件通常存放在components
文件夾。通過點擊導航,視覺效果上“消失” 了的路由組件,默認是被卸載掉的,需要的時候再去掛載。
<template><div class="app"><h2 class="title">Vue路由測試</h2><!-- 導航區 --><div class="navigate"><RouterLink to="/home" active-class="active">首頁</RouterLink><RouterLink to="/news" active-class="active">新聞</RouterLink><RouterLink to="/about" active-class="active">關于</RouterLink></div><!-- 展示區 --><div class="main-content"><RouterView></RouterView></div></div>
</template><script lang="ts" setup name="App">import {RouterLink,RouterView} from 'vue-router'
</script>
4.2.路由器工作模式
history
模式
優點:
URL
更加美觀,不帶有#
,更接近傳統的網站URL
。缺點:后期項目上線,需要服務端配合處理路徑問題,否則刷新會有
404
錯誤。
const router = createRouter({history:createWebHistory(), //history模式/******/
})
hash
模式
優點:兼容性更好,因為不需要服務器端處理路徑。
缺點:
URL
帶有#
不太美觀,且在SEO
優化方面相對較差
const router = createRouter({history:createWebHashHistory(), //hash模式/******/
})
4.3.to的兩種寫法?
<RouterLink to="/home">主頁</RouterLink>
<RouterLink to="{path:'/home'}">主頁</RouterLink>
4.4.命名路由
在路由表中添加name屬性
可以通過<RouterLink to="{name:'zhuye'}"><RouterLink>直接跳轉?
?4.5.嵌套路由(子路由)
在一個路由下面增加children屬性,再寫入其他路由
const router = createRouter({history:createWebHistory(),routes:[{name:'zhuye',path:'/home',component:Home},{name:'xinwen',path:'/news',component:News,children:[{name:'xiang',path:'detail',component:Detail}]},{name:'guanyu',path:'/about',component:About}]
})
export default router
4.6.路由傳參
query參數
-
傳遞參數
<!-- 跳轉并攜帶query參數(to的字符串寫法) --> <router-link to="/news/detail?a=1&b=2&content=歡迎你">跳轉 </router-link><!-- 跳轉并攜帶query參數(to的對象寫法) --> <RouterLink :to="{//name:'xiang', //用name也可以跳轉path:'/news/detail',query:{id:news.id,title:news.title,content:news.content}}" >{{news.title}} </RouterLink>
-
接收參數:
import{useRoute} from 'vue-router' const route = useRoute() console.log(route.query)
params參數
-
傳遞參數
<!-- 跳轉并攜帶params參數(to的字符串寫法) --> <RouterLink :to="`/news/detail/001/新聞001/內容001`">{{news.title}}</RouterLink><!-- 跳轉并攜帶params參數(to的對象寫法) --> <RouterLink :to="{name:'xiang', //用name跳轉params:{id:news.id,title:news.title,content:news.title}}" >{{news.title}} </RouterLink>
-
接收參數:
import {useRoute} from 'vue-router' const route = useRoute() // 打印params參數 console.log(route.params)
3.占位
[name:'xinwen',path:'/news',component:News,children:[name:'xiang',//占位!!!!path: 'detail/:id/:title/:content',component:Detail[]
注意
備注1:傳遞
params
參數時,若使用to
的對象寫法,必須使用name
配置項,不能用path
。備注2:傳遞
params
參數時,需要提前在規則中占位。
4.7. 路由的prop配置
使傳參更優雅
{name:'xiang',path:'detail/:id/:title/:content',component:Detail,// props的對象寫法,作用:把對象中的每一組key-value作為props傳給Detail組件// props:{a:1,b:2,c:3}, // props的布爾值寫法,作用:把收到了每一組params參數,作為props傳給Detail組件// props:true// props的函數寫法,作用:把返回的對象中每一組key-value作為props傳給Detail組件props(route){return route.query}
}
?4.8.replace屬性
控制路由跳轉時操作瀏覽器歷史記錄模式
瀏覽器的歷史記錄有兩種寫入方式:分別為
push
和replace
:
push
是追加歷史記錄(默認值)。replace
是替換當前記錄。開啟
replace
模式:<RouterLink replace .......>News</RouterLink>
?4.9.編程式導航
在vue3中,$route和$router變成了兩個hook,就是在導航區以外的地方通過一些操作實現路由跳轉
<template><div>當前路由路徑: {{ route.path }}</div>
</template><script setup>
import { useRoute } from 'vue-router';const route = useRoute();
</script>
<template><button @click="goToHome">前往首頁</button>
</template><script setup>
import { useRouter } from 'vue-router';const router = useRouter();const goToHome = () => {router.push('/home');
};
</script>
補充知識點,定時任務?
//掛載后,頁面三秒自動跳轉
onMounted(()=>{
router.push('/home')
},3000)
?4.10.重定向
將特定的路徑,重新定向到已經有的路由,通過redirect
[path:'/',redirect:'/about'
]
5.pinia
5.1.搭建環境
step1:npm install pinia
step2:操作 src/main.ts
import { createApp } from 'vue'
import App from './App.vue'/* 引入createPinia,用于創建pinia */
import { createPinia } from 'pinia'/* 創建pinia */
const pinia = createPinia()
const app = createApp(App)/* 使用插件 */{}
app.use(pinia)
app.mount('#app')
?5.2.存儲+讀取數據
store是pinia的一個功能部件,我的理解是可以提取公共的數據或者函數供其他組件使用
在src/store中創建文件
具體編碼src/store/count.ts
//引入defineStore用于創建store
import {defineStore} from 'pinia'//定義并暴露一個store
export const useCountstore = defineStore('count',{//動作actions:{},//狀態state(){return {sum:6}},//計算getters:{}
})
使用?
<template><h1>當前的求和為:{{countStore.sum}}</h1>
</template>
<script setup lang="ts" name="count">
//引入對應的useXxxStore
import {useCountStore} from '@/src/store/count'
//調用對應的useXxxStore得到對應的store
const countStore = useCountStore()
</script>
5.3.修改數據
1.直接在調用的地方加(vue3特性)
countStore.sum = 666
2.批量修改,通過patch函數
countStore.$patch({
sum:999
age:111? ? ? ??
})
3.通過store里面的action創建修改store數據的方法
import {defineStore} from 'pinia'export const useCountStore = defineStore('count' ,{actions: {//加increment(value:number) {if (this.sum < 10) {//操作countStore中的sumthis.sum += value}},//減decrement(value:number){if(this.sum > 1){this.sum -= value}}},/*************/
})
?5.4.storeToRefs
借助storeToRefs會將store中的數據轉化為ref對象,而store中的函數不變
通過toRefs會將store的所有都轉化為ref對象,包括函數
<template><div class="count"><h2>當前求和為:{{sum}}</h2></div>
</template><script setup lang="ts" name="Count">import { useCountStore } from '@/store/count'/* 引入storeToRefs */import { storeToRefs } from 'pinia'/* 得到countStore */const countStore = useCountStore()/* 使用storeToRefs轉換countStore,隨后解構 */const {sum} = storeToRefs(countStore)
</script>
5.5.getters
當state
中的數據,需要經過處理后再使用時,可以使用getters
配置。{感覺有點雞肋,在state不是也可以嗎},,記得在使用時和state一起import
// 引入defineStore用于創建store
import {defineStore} from 'pinia'// 定義并暴露一個store
export const useCountStore = defineStore('count',{// 動作actions:{/************/},// 狀態state(){return {sum:1,school:'atguigu'}},// 計算getters:{bigSum:(state):number => state.sum *10,upperSchool():string{return this. school.toUpperCase()}}
})
5.6.$subscribe
監視變化,和watch類似
mutate:關于狀態變化的信息
state:最新的state對象
talkStore.$subscribe((mutate,state)=>{console.log('LoveTalk',mutate,state)
})
?5.7.store組合式寫法
將數據和方法寫在一個函數里面,別忘了最后需要return交出去
import {defineStore} from 'pinia'
import { ref } from 'vue';export const useSumStore = defineStore('sum' ,()=>{const sum = ref(999)function add(){sum.value++
}return {sum,add}
})
6.組件通信
6.1.props
父傳子,引入子組件的時候直接附帶需要傳遞的值
父傳子
<template><div class="father"><h3>父組件,</h3><Child :car="car" :getToy="getToy"/></div>
</template><script setup lang="ts" name="Father">import Child from './Child.vue'import { ref } from "vue";// 數據const car = ref('奔馳')
</script>
子接受,通過defineProps
defineProps(['car'])
?
?子傳父,需要通過父傳遞的函數把值傳遞給父,就像父定義了一個構造函數,但是由子來調用這個構造函數從而獲取具體的值
子調用父的函數
<template><div class="child"><h3>子組件</h3><h4>我的玩具:{{ toy }}</h4><button @click="getToy(toy)">玩具給父親</button></div>
</template><script setup lang="ts" name="Child">import { ref } from "vue";const toy = ref('奧特曼')defineProps(['getToy'])
</script>
父通過子調用函數獲取值
<template><div class="father"><h3>父組件,</h3><h4>兒子給的玩具:{{ toy }}</h4><Child :getToy="getToy"/></div>
</template><script setup lang="ts" name="Father">import Child from './Child.vue'import { ref } from "vue";// 數據const toy = ref()// 方法function getToy(value:string){toy.value = value}
</script>
6.2 自定義事件
我認為這又有點像一種高級的監聽機制,父組件在子組件綁定一個事件并聲明一個回調函數,只要子組件發生這個事件,父組件就會調用這個回調函數,并且還會受到子組件的值
主要是注意一些格式,子組件在接受事件的時候 通過const emits = defineEmits(['send-toy'])?
使用時通過emit('send-toy' ,toy)來響應事件,從而時父組件接受事件附帶的值并執行回調函數
?
6.3mitt
? ? ? ? 好像一個第三方的自定義事件功能,接收數據者定義事件,提供數據者觸發事件,相比自定義事件,更“自由靈活”
step1:npm i mitt
step2:在util文件夾中創建emitter.ts
//引入emit
import mitt from "mitt"//創建emitter
const emitter = mitt()//創建并暴露mitt
export default emitter
?綁定事件
emitter.on('send-toy' (value)=>{ console.log("接受value并執行回調函數")})
觸發事件
emitter.emit('send-toy' ,666)
注意,在組件卸載時候,盡量解綁當前組件綁定的事件,避免消耗內存
onUmMounted(()=>{? emitter.off('send-toy')})
6.4.v-model
v-model的本質
<!-- 使用v-model指令 -->
<input type="text" v-model="userName"><!-- v-model的本質是下面這行代碼 -->
<input type="text" :value="userName" @input="userName =(<HTMLInputElement>$event.target).value"
>
?
6.5.$attrs
通常用于父與孫的傳遞,但是中間的橋梁是子組件,
具體說明:$attrs
是一個對象,包含所有父組件傳入的標簽屬性。(個人理解:動態的資源集合)
注意:$attrs會排除props中已經聲明的屬性(相當于已經被用了),但把剩下的仍在$attrs中
父組件
<template><div class="father"><h3>父組件</h3><Child :a="a" :b="b" :c="c" :d="d" v-bind="{x:100,y:200}" :updateA="updateA"/></div>
</template><script setup lang="ts" name="Father">import Child from './Child.vue'import { ref } from "vue";let a = ref(1)let b = ref(2)let c = ref(3)let d = ref(4)function updateA(value){a.value = value}
</script>
子組件
<template><div class="child"><h3>子組件</h3><GrandChild v-bind="$attrs"/></div>
</template><script setup lang="ts" name="Child">import GrandChild from './GrandChild.vue'
</script>
孫組件
<template><div class="grand-child"><h3>孫組件</h3><h4>a:{{ a }}</h4><h4>b:{{ b }}</h4><h4>c:{{ c }}</h4><h4>d:{{ d }}</h4><h4>x:{{ x }}</h4><h4>y:{{ y }}</h4><button @click="updateA(666)">點我更新A</button></div>
</template><script setup lang="ts" name="GrandChild">defineProps(['a','b','c','d','x','y','updateA'])
</script>
6.6.$refs,$parent
-
概述:
$refs
用于 :父→子。$parent
用于:子→父。
-
原理如下:
屬性 說明 $refs
值為對象,包含所有被 ref
屬性標識的DOM
元素或組件實例。$parent
值為對象,當前組件的父組件實例對象。
但是需要用?defineExpose暴露出去,使用時候不需要顯式傳遞,直接用
6.7. provide和inject
- 在祖先組件中通過
provide
配置向后代組件提供數據 - 在后代組件中通過
inject
配置來聲明接收數據
在父組件中,通過provide提供數據
<template><div class="father"><h3>父組件</h3><Child/></div>
</template><script setup lang="ts" name="Father">import Child from './Child.vue'import { ref,reactive,provide } from "vue";// 數據let money = ref(100)let car = reactive({brand:'奔馳',price:100})// 用于更新money的方法function updateMoney(value:number){money.value += value}// 提供數據provide('moneyContext',{money,updateMoney})provide('car',car)
</script>
后代中通過inject接受數據,盡量代碼有默認值
<template><div class="grand-child"><h3>我是孫組件</h3><h4>資產:{{ money }}</h4><h4>汽車:{{ car }}</h4><button @click="updateMoney(6)">點我</button></div>
</template><script setup lang="ts" name="GrandChild">import { inject } from 'vue';// 注入數據let {money,updateMoney} = inject('moneyContext',{money:0,updateMoney:(x:number)=>{}})let car = inject('car')
?
?6.7.solt
1.默認插槽
父組件在聲明子組件時會傳遞一些供以顯示的數據,這時候用插槽為這些數據的顯示提供位置
父組件中:<Category title="今日熱門游戲"><ul><li v-for="g in games" :key="g.id">{{ g.name }}</li></ul></Category>
子組件中:<template><div class="item"><h3>{{ title }}</h3><!-- 默認插槽 --><slot></slot></div></template>
2.具名插槽
指定插在哪個位置,通過v-slot或者#slot
父組件中:<Category title="今日熱門游戲"><template v-slot:s1><ul><li v-for="g in games" :key="g.id">{{ g.name }}</li></ul></template><template #s2><a href="">更多</a></template></Category>
子組件中:<template><div class="item"><h3>{{ title }}</h3><slot name="s1"></slot><slot name="s2"></slot></div></template>
3.作用域插槽
數據在組件的自身,但根據數據生成的結構需要組件的使用者來決定
子組件通過在插槽聲明的位置聲明數據,由使用者操作
父組件中:<Game v-slot="params"><!-- <Game v-slot:default="params"> --><!-- <Game #default="params"> --><ul><li v-for="g in params.games" :key="g.id">{{ g.name }}</li></ul></Game>子組件中:<template><div class="category"><h2>今日游戲榜單</h2><slot :games="games" a="哈哈"></slot></div></template><script setup lang="ts" name="Category">import {reactive} from 'vue'let games = reactive([{id:'asgdytsa01',name:'英雄聯盟'},{id:'asgdytsa02',name:'王者榮耀'},{id:'asgdytsa03',name:'紅色警戒'},{id:'asgdytsa04',name:'斗羅大陸'}])</script>
7.其他API
7.1.shallowRef 與 shallowReactive?
繞開深度響應,提升性能
shallowRef
作用:創建一個響應式數據,但只對頂層【屬性】進行響應式處理。
用法:
let myVar = shallowRef(initialValue);
特點:只跟蹤引用值的變化,不關心值內部的屬性變化。
shallowReactive
作用:創建一個淺層響應式對象,只會使對象的【最頂層屬性】變成響應式的,對象內部的嵌套屬性則不會變成響應式的
用法:
const myObj = shallowReactive({ ... });
特點:對象的頂層屬性是響應式的,但嵌套對象的屬性不是。
?
7.2.readonly 與 shallowReadonly
readonly
作用:用于創建一個對象的深只讀副本。
用法:
const original = reactive({ ... }); const readOnlyCopy = readonly(original);
特點:
- 對象的所有嵌套屬性都將變為只讀。
- 任何嘗試修改這個對象的操作都會被阻止(在開發模式下,還會在控制臺中發出警告)。
應用場景:
- 創建不可變的狀態快照。
- 保護全局狀態或配置不被修改。
shallowReadonly
作用:與?
readonly
?類似,但只作用于對象的頂層屬性。用法:
const original = reactive({ ... }); const shallowReadOnlyCopy = shallowReadonly(original);
特點:
只將對象的頂層屬性設置為只讀,對象內部的嵌套屬性仍然是可變的。
適用于只需保護對象頂層屬性的場景。
7.3.?toRaw 與 markRaw
toRaw
????????作用:用于獲取一個響應式對象的原始對象,?toRaw
?返回的對象不再是響應式的,不會觸發視圖更新。
markRaw
????????作用:標記一個對象,使其永遠不會變成響應式的。
import { reactive,toRaw,markRaw,isReactive } from "vue";/* toRaw */
// 響應式對象
let person = reactive({name:'tony',age:18})
// 原始對象
let rawPerson = toRaw(person)/* markRaw */
let citysd = markRaw([{id:'asdda01',name:'北京'},{id:'asdda02',name:'上海'},{id:'asdda03',name:'天津'},{id:'asdda04',name:'重慶'}
])
7.4.customRef
自定義的ref,可以實現特殊的邏輯,一般把自定義的ref封裝為一個hook
import {customRef } from "vue";export default function(initValue:string,delay:number){let msg = customRef((track,trigger)=>{let timer:numberreturn {get(){track() // 告訴Vue數據msg很重要,要對msg持續關注,一旦變化就更新return initValue},set(value){clearTimeout(timer)timer = setTimeout(() => {initValue = valuetrigger() //通知Vue數據msg變化了}, delay);}}}) return {msg}
}
8.Vue3新組件?
8.1.Teleport
將窗口移動到指定位置
<teleport to='body' ><div class="modal" v-show="isShow"><h2>我是一個彈窗</h2><p>我是彈窗中的一些內容</p><button @click="isShow = false">關閉彈窗</button></div>
</teleport>
?
8.2.Suspense
- 等待異步組件時渲染一些額外內容,讓應用有更好的用戶體驗
-
<template><div class="app"><h3>我是App組件</h3><Suspense>//異步組件加載完成后顯示內容<template v-slot:default><Child/></template>//異步組件加載過程中顯示內容,加載之后消失<template v-slot:fallback><h3>加載中.......</h3></template></Suspense></div> </template>