總結(尚硅谷Vue3入門到實戰,最新版vue3+TypeScript前端開發教程)

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

使用原則:

  1. 若需要一個基本類型的響應式數據,必須使用ref
  2. 若需要一個響應式對象,層級不深,refreactive都可以。
  3. 若需要一個響應式對象,且層級較深,推薦使用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對象

注意:toRefstoRef功能一致,但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

掛載階段:onBeforeMountonMounted

更新階段:onBeforeUpdateonUpdated

卸載階段:onBeforeUnmountonUnmounted

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>

  1. 路由組件通常存放在pages?或?views文件夾,一般組件通常存放在components文件夾。

  2. 通過點擊導航,視覺效果上“消失” 了的路由組件,默認是被卸載掉的,需要的時候再去掛載

<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參數

  1. 傳遞參數

    <!-- 跳轉并攜帶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>
    
  2. 接收參數:

    import{useRoute} from 'vue-router'
    const route = useRoute()
    console.log(route.query)

params參數

  1. 傳遞參數

    <!-- 跳轉并攜帶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>
    
  2. 接收參數:

    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屬性

控制路由跳轉時操作瀏覽器歷史記錄模式

  1. 瀏覽器的歷史記錄有兩種寫入方式:分別為pushreplace

    • push是追加歷史記錄(默認值)。
    • replace是替換當前記錄。
  2. 開啟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

  1. 概述:

    • $refs用于 :父→子。
    • $parent用于:子→父。
  2. 原理如下:

    屬性說明
    $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

  1. 作用:創建一個響應式數據,但只對頂層【屬性】進行響應式處理。

  2. 用法:

    let myVar = shallowRef(initialValue);
    
  3. 特點:只跟蹤引用值的變化,不關心值內部的屬性變化。

shallowReactive

  1. 作用:創建一個淺層響應式對象,只會使對象的【最頂層屬性】變成響應式的,對象內部的嵌套屬性則不會變成響應式的

  2. 用法:

    const myObj = shallowReactive({ ... });
  3. 特點:對象的頂層屬性是響應式的,但嵌套對象的屬性不是。

?

7.2.readonly 與 shallowReadonly

readonly

  1. 作用:用于創建一個對象的深只讀副本。

  2. 用法:

    const original = reactive({ ... });
    const readOnlyCopy = readonly(original);
    
  3. 特點:

    • 對象的所有嵌套屬性都將變為只讀。
    • 任何嘗試修改這個對象的操作都會被阻止(在開發模式下,還會在控制臺中發出警告)。
  4. 應用場景:

    • 創建不可變的狀態快照。
    • 保護全局狀態或配置不被修改。

shallowReadonly

  1. 作用:與?readonly?類似,但只作用于對象的頂層屬性。

  2. 用法:

    const original = reactive({ ... });
    const shallowReadOnlyCopy = shallowReadonly(original);
    
  3. 特點:

    • 只將對象的頂層屬性設置為只讀,對象內部的嵌套屬性仍然是可變的。

    • 適用于只需保護對象頂層屬性的場景。

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>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/71365.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/71365.shtml
英文地址,請注明出處:http://en.pswp.cn/web/71365.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

SolidWorks 轉 PDF3D 技術詳解

在現代工程設計與制造流程中&#xff0c;不同軟件間的數據交互與格式轉換至關重要。將 SolidWorks 模型轉換為 PDF3D 格式&#xff0c;能有效解決模型展示、數據共享以及跨平臺協作等問題。本文將深入探討 SolidWorks 轉 PDF3D 的技術原理、操作流程及相關注意事項&#xff0c;…

【深度學習CV】【圖像分類】從CNN(卷積神經網絡)、ResNet遷移學習到GPU高效訓練優化【案例代碼】詳解

摘要 本文分類使用的是resNet34,什么不用yolo v8&#xff0c;yolo v10系列,雖然他們也可以分類&#xff0c;因為yolo系列模型不純粹&#xff0c;里面包含了目標檢測的架構&#xff0c;所以分類使用的是resNet 本文詳細介紹了三種不同的方法來訓練卷積神經網絡進行 CIFAR-10 圖…

OPPO Find N5折疊手機:創新與實用的完美融合,FPC應用展現科技魅力【新立電子】

OPPO Find N5作為2025年新出世的折疊手機&#xff0c;以其卓越的設計、強大的性能以及創新的技術&#xff0c;為消費者帶來了全新的使用體驗。FPC&#xff08;柔性電路板&#xff09;在其中的運用&#xff0c;也進一步提升了手機的整體性能和用戶體驗。 OPPO Find N5的最大亮點…

【AD】PCB增加相關圖層——以機械層為例

問題&#xff1a;圖中PCB僅有機械層1和機械層2&#xff0c;想要在加一個機械層3 解決 1.點擊視圖—面板—View Configuration&#xff0c;選中機械層右鍵單擊增加層&#xff0c;其他層類似

Qt5 C++ QMap使用總結

文章目錄 功能解釋代碼使用案例代碼解釋注意事項代碼例子參考 功能解釋 QList<T> QMap::values() const Returns a list containing all the values in the map, in ascending order of their keys. If a key is associated with multiple values, all of its values wi…

測試用例總結

一、通用測試用例八要素   1、用例編號&#xff1b;    2、測試項目&#xff1b;   3、測試標題&#xff1b; 4、重要級別&#xff1b;    5、預置條件&#xff1b;    6、測試輸入&#xff1b;    7、操作步驟&#xff1b;    8、預期輸出 二、具體分析通…

不用寫代碼,批量下載今日頭條文章導出excel和pdf

前幾天有人問我怎么批量抓取今日頭條某個號的所有文章數據&#xff0c;需要文章鏈接&#xff0c;標題和時間&#xff0c;但是不會寫代碼&#xff0c;于是我寫了個簡單的教程 這里以渤海小吏為例 首先用edge瀏覽器安裝web-scraper瀏覽器擴展 然后打開瀏覽器控制臺&#xff0c;找…

Starrocks 寫入報錯 primary key memory usage exceeds the limit

背景 本文基于 StarRocks 3.3.5 單個Starrocks BE配置是 16CU 32GB 在Flink Yaml CDC 任務往 Starrocks寫數據的過程中&#xff0c;突然遇到了primary key memory usage exceeds the limit 問題&#xff0c;具體如下&#xff1a; java.lang.RuntimeException: com.starrocks.…

Django:文件上傳時報錯in a frame because it set ‘X-Frame-Options‘ to ‘deny‘.

即&#xff1a;使用Content-Security-Policy 1.安裝Django CSP中間件&#xff1a; pip install django-csp 2.更改項目配置&#xff1a; # settings.py MIDDLEWARE [...csp.middleware.CSPMiddleware,... ]CSP_DEFAULT_SRC ("self",) CSP_FRAME_ANCESTORS (&q…

利用Adobe Acrobat 實現PPT中圖片分辨率的提升

1. 下載適用于 Windows 的 64 位 Acrobat 注冊方式參考&#xff1a;https://ca.whu.edu.cn/knowledge.html?type1 2. 將ppt中需要提高分辨率的圖片復制粘貼到新建的pptx問價中&#xff0c;然后執行“文件—>導出---->創建PDF、XPS文檔” 3. 我們會發現保存下來的distrib…

【Python爬蟲】爬取公共交通路網數據

程序來自于Github&#xff0c;以下這篇博客作為完整的學習記錄&#xff0c;也callback上一篇爬取公共交通站點的博文。 Bardbo/get_bus_lines_and_stations_data_from_gaode: 這個項目是基于高德開放平臺和公交網獲取公交線路及站點數據&#xff0c;并生成shp文件&#xff0c;…

Stable Diffusion模型高清算法模型類詳解

Stable Diffusion模型高清算法模型類詳細對比表 模型名稱核心原理適用場景參數建議顯存消耗細節增強度優缺點4x-UltraSharp殘差密集塊(RDB)結構優化紋理生成真實人像/建筑攝影重繪幅度0.3-0.4&#xff0c;分塊尺寸768px★★★★★☆皮膚紋理細膩&#xff0c;但高對比場景易出現…

VUE_使用Vite構建vue項目

創建項目 // 安裝vite npm install vite// 創建名為vite-app的項目 npm create vite vite-app --template vue// 到項目目錄 cd vite-app// 安裝依賴 npm install// 運行項目 npm run dev// 打包 npm run build// 打包預覽 npm run serve 增加路由 // 安裝路由 npm add vue-r…

ctf網絡安全賽題

CTF簡介 CTF&#xff08;Capture The Flag&#xff09;中文一般譯作奪旗賽&#xff0c;在網絡安全領域中指的是網絡安全技術人員之間進行技術競技的一種比賽形式。CTF起源于1996年DEFCON全球黑客大會&#xff0c;以代替之前黑客們通過互相發起真實攻擊進行技術比拼的方式。發展…

【朝夕教育】《鴻蒙原生應用開發從零基礎到多實戰》004-TypeScript 中的泛型

標題詳情作者簡介愚公搬代碼頭銜華為云特約編輯&#xff0c;華為云云享專家&#xff0c;華為開發者專家&#xff0c;華為產品云測專家&#xff0c;CSDN博客專家&#xff0c;CSDN商業化專家&#xff0c;阿里云專家博主&#xff0c;阿里云簽約作者&#xff0c;騰訊云優秀博主&…

性能測試監控工具jmeter+grafana

1、什么是性能測試監控體系&#xff1f; 為什么要有監控體系&#xff1f; 原因&#xff1a; 1、項目-日益復雜&#xff08;內部除了代碼外&#xff0c;還有中間件&#xff0c;數據庫&#xff09; 2、一個系統&#xff0c;背后可能有多個軟/硬件組合支撐&#xff0c;影響性能的因…

互聯網時代如何保證數字足跡的安全,以防個人信息泄露?

用戶在網絡上所做的幾乎所有事情&#xff0c;包括瀏覽、社交媒體活動、搜索查詢、在線訂閱&#xff0c;甚至購物&#xff0c;都會留下一條數據線索&#xff0c;這些數據可用于創建用戶在線身份的詳細檔案。如果這些信息暴露&#xff0c;惡意行為者可能會利用它們將用戶置于各種…

C# IEquatable<T> 使用詳解

總目錄 前言 在 C# 開發中&#xff0c;IEquatable<T> 是一個泛型接口&#xff0c;用于定義類型的相等性比較邏輯。通過實現 IEquatable<T>&#xff0c;可以為自定義類型提供高效的、類型安全的相等性比較方法。本文將詳細介紹 IEquatable<T> 的使用方法、應…

web第四天

Dom操作元素 innerText、innerHTML、value(input and textarea用到) 更改屬性&#xff0c;樣式 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-wid…

LabVIEW基于IMAQ實現直線邊緣檢測

本程序基于 NI Vision Development 模塊&#xff0c;通過 IMAQ Find Straight Edges 函數&#xff0c;在指定 ROI&#xff08;感興趣區域&#xff09; 內檢測多條直線邊緣。用戶可 動態調整檢測參數 或 自定義ROI&#xff0c;實時觀察識別效果&#xff0c;適用于 高精度視覺檢測…