Vue3使用slot插槽的實現(xiàn)
概述
插槽在真實的開發(fā)中使用非常的多,比如我們?nèi)ビ靡恍┑谌浇M件庫的時候,通常都需要通過自定義插槽來實現(xiàn)內(nèi)容的自定義。
在Vue3中使用插槽非常的簡單。
插槽相當(dāng)于在組件中給你預(yù)留一塊位置,你可以將自己的vue3相關(guān)的代碼插入到這個位置中。
基本用法
我們創(chuàng)建src/components/Demo31.vue,代碼如下:
<template>
<div>
<h3>我在下面給你預(yù)留一個插槽,你可以傳Vue3的代碼進來</h3>
<slot></slot>
</div>
</template>
接著,我們修改src/App.vue:
<script setup>
import Demo from "./components/Demo31.vue"
</script>
<template>
<h1>歡迎跟著Python私教一起學(xué)習(xí)Vue3入門課程</h1>
<hr>
<demo>
<h3>這里的內(nèi)容會被填充到插槽1</h3>
<h3>這里的內(nèi)容會被填充到插槽2</h3>
<h3>這里的內(nèi)容會被填充到插槽3</h3>
</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/Demo31.vue"
</script>
<template>
<h1>歡迎跟著Python私教一起學(xué)習(xí)Vue3入門課程</h1>
<hr>
<demo>
<h3>這里的內(nèi)容會被填充到插槽1</h3>
<h3>這里的內(nèi)容會被填充到插槽2</h3>
<h3>這里的內(nèi)容會被填充到插槽3</h3>
</demo>
</template>
src/components/Demo31.vue
<template>
<div>
<h3>我在下面給你預(yù)留一個插槽,你可以傳Vue3的代碼進來</h3>
<slot></slot>
</div>
</template>
啟動方式
yarn yarn dev
瀏覽器訪問:http://localhost:5173/
到此這篇關(guān)于Vue3使用slot插槽的實現(xiàn)的文章就介紹到這了,更多相關(guān)Vue3 slot插槽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mpvue性能優(yōu)化實戰(zhàn)技巧(小結(jié))
這篇文章主要介紹了mpvue性能優(yōu)化實戰(zhàn)技巧(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
關(guān)于vue組件的更新機制?resize()?callResize()
這篇文章主要介紹了關(guān)于vue組件的更新機制?resize()?callResize(),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue3優(yōu)雅的實現(xiàn)跨組件通信的常用方法總結(jié)
開發(fā)中經(jīng)常會遇到跨組件通信的場景,props?逐層傳遞的方法實在是太不優(yōu)雅了,所以今天總結(jié)下可以更加簡單的跨組件通信的一些方法,文中通過代碼實例講解的非常詳細,需要的朋友可以參考下2023-11-11

