惠州有哪些做網(wǎng)站的公司百度熱門
【Vue3】默認(rèn)插槽
- 背景
- 簡介
- 開發(fā)環(huán)境
- 開發(fā)步驟及源碼
背景
隨著年齡的增長,很多曾經(jīng)爛熟于心的技術(shù)原理已被歲月摩擦得愈發(fā)模糊起來,技術(shù)出身的人總是很難放下一些執(zhí)念,遂將這些知識整理成文,以紀(jì)念曾經(jīng)努力學(xué)習(xí)奮斗的日子。本文內(nèi)容并非完全原創(chuàng),大多是參考其他文章資料整理所得,感謝每位技術(shù)人的開源精神。
簡介
本文介紹 Vue3 中如何默認(rèn)插槽。
在封裝組件時可能存在需要動態(tài)展現(xiàn)的內(nèi)容區(qū)域,即組件中某一內(nèi)容區(qū)域在組件定義時并不能確定展現(xiàn)內(nèi)容,只有當(dāng)組件被引用時才由父組件指定要展現(xiàn)的內(nèi)容。Vue 提供插槽(<slot>
)作為動態(tài)展現(xiàn)內(nèi)容區(qū)域的占位符,父組件可以在此占位符區(qū)域內(nèi)填充具體的展現(xiàn)內(nèi)容。
Vue 中的插槽包含三類:
- 默認(rèn)插槽
- 具名插槽
- 作用域插槽
開發(fā)環(huán)境
分類 | 名稱 | 版本 |
---|---|---|
操作系統(tǒng) | Windows | Windows 11 |
IDE | Visual Studio Code | 1.91.1 |
開發(fā)步驟及源碼
1> 創(chuàng)建 Vue3 工程,參考:【Vue3】工程創(chuàng)建及目錄說明。
2> 刪除 src
目錄下 assets
和 components
目錄。
3> 修改 src
目錄下 main.ts
。
import { createApp } from 'vue'
import App from './App.vue'createApp(App).mount('#app')
4> 自定義帶插槽的功能組件。
<template><div class="store"><h2>帶插槽的功能組件</h2><slot></slot></div>
</template><script setup lang="ts">
</script><style scoped lang="scss">
.store {background-color: green;box-shadow: 0 0 10px;color: white;padding: 10px;width: 300px;
}
</style>
注意:需要執(zhí)行 npm install -D sass
命令安裝 CSS 預(yù)處理器。
5> 修改 Vue 根組件 src/App.vue
,引用自定義功能組件。
<template><div class="root"><h1 ref="title">App組件</h1><div class="stores"><Store><ul><li v-for="film in films" :key="film.id">{{ film.name }}</li></ul></Store><Store><ol><li v-for="film in films" :key="film.id">{{ film.name }}</li></ol></Store><Store><h4 v-for="film in films" :key="film.id"># {{ film.name }}</h4></Store></div></div>
</template><script setup lang="ts">
import Store from './components/Store.vue'
import { reactive } from 'vue'const films = reactive([{ id: '001', name: '哈利波特與魔法石'},{ id: '002', name: '哈利波特與密室'},{ id: '003', name: '哈利波特與阿茲卡班的囚徒'},{ id: '004', name: '哈利波特與鳳凰社'},
])
</script><style scoped lang="scss">
.root {background-color: orange;box-shadow: 0 0 10px;padding: 20px;h1 {text-align: center;}.stores {display: flex;justify-content: space-evenly;}
}
</style>
6> 執(zhí)行命令 npm run dev
啟動應(yīng)用,瀏覽器訪問:http://localhost:5173/
。