Vue3中同時定義多個插槽的實現(xiàn)示例
更新時間:2023年12月21日 10:40:50 作者:Python私教
本文主要介紹了Vue3中同時定義多個插槽的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
概述
當你想要給外部預留多個位置的時候,具名插槽就非常有用了。
比如,我們定義一個卡片,讓別人使用的時候,標題可以自定義,內容也可以自定義,這個時候就需要兩個插槽。
基本用法
我們創(chuàng)建src/components/Demo32.vue,代碼如下:
<template> <div> <slot name="title"> <h3>卡片默認標題</h3> </slot> <slot name="content"> <div>卡片默認內容</div> </slot> </div> </template>
接著,我們修改src/App.vue:
<script setup> import Demo from "./components/Demo32.vue" </script> <template> <h1>歡迎跟著Python私教一起學習Vue3入門課程</h1> <hr> <demo/> <hr> <demo> <template #title> <h3>自定義的標題</h3> </template> <template #content> <div>自定義的內容</div> </template> </demo> </template>
然后,我們?yōu)g覽器訪問:http://localhost:5173/
完整代碼
package.json
{ "name": "hello", "private": true, "version": "0.1.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build" }, "dependencies": { "vue": "^3.3.8" }, "devDependencies": { "@vitejs/plugin-vue": "^4.5.0", "vite": "^5.0.0" } }
vite.config.js
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], })
index.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" rel="external nofollow" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + Vue</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.js"></script> </body> </html>
src/main.js
import { createApp } from 'vue' import App from './App.vue' createApp(App).mount('#app')
src/App.vue
<script setup> import Demo from "./components/Demo32.vue" </script> <template> <h1>歡迎跟著Python私教一起學習Vue3入門課程</h1> <hr> <demo/> <hr> <demo> <template #title> <h3>自定義的標題</h3> </template> <template #content> <div>自定義的內容</div> </template> </demo> </template>
src/components/Demo32.vue
<template> <div> <slot name="title"> <h3>卡片默認標題</h3> </slot> <slot name="content"> <div>卡片默認內容</div> </slot> </div> </template>
啟動方式
yarn yarn dev
瀏覽器訪問:http://localhost:5173/
到此這篇關于Vue3中同時定義多個插槽的實現(xiàn)示例的文章就介紹到這了,更多相關Vue3同時定義多個插槽內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue中封裝axios并實現(xiàn)api接口的統(tǒng)一管理
這篇文章主要介紹了vue中封裝axios并實現(xiàn)api接口的統(tǒng)一管理的方法,幫助大家更好的理解和使用vue,感興趣的朋友可以了解下2020-12-12VSCode寫vue項目一鍵生成.vue模版,修改定義其他模板的方法
這篇文章主要介紹了VSCode寫vue項目一鍵生成.vue模版,修改定義其他模板的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04