--- tags: Javascript, Vue --- # Vue slot插巢 ## 基本使用 在某些情況下,希望能將`template`傳遞給子組件,並讓此段`template`在子組件中渲染。 以下是vue官方圖片  也就是在`FancyButton`組件中插入`slot tag`,就可以將`Click Me`帶入到`FancyButton`組件的`slot`中 以上範例會轉換成以下: ```htmlembedded= <button class="fancy-btn"> Click me! </button> ``` ## 命名Slots 可以給`slot`命名,讓他在指定位置傳遞,假設有一個`solt`命名為`header`,`<slot name="header"></slot>`若要傳遞給名為`header`的`slot`可以使用`<template v-slot:header>`或是縮寫 `<template #header>` 官方圖片如下  範例:  ```htmlembedded= <body> <div id="app"> <h3>slot</h3> <card> <template #img> <img src="https://www.w3schools.com/images/lamp.jpg" class="card-img-top" alt="Lamp" width="200" height="200"> </template> <template #title> <p>我是標題</p> </template> <template #body> <p>內文在這</p> </template> </card> </div> <script type="module"> const app = Vue.createApp({ }); app.component("card", { data() { return {}; }, template: ` <div class="card" style="width: 18rem;"> <slot name="img"></slot> <div class="card-body"> <h5 class="card-title"><slot name="title"></slot></h5> <p class="card-text"><slot name="body"></slot></p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div>`, }); app.mount("#app"); </script> </body> ``` ### 動態插槽 動態指令參數也適用於`v-slot` ```htmlembedded= <base-layout> <template v-slot:[dynamicSlotName]> ... </template> <!-- with shorthand --> <template #[dynamicSlotName]> ... </template> </base-layout> ``` ## 傳遞資料 在某些情況下,如果`slot`插槽的內容可以使用來自父組件範圍和子組件範圍的數據,可能會很有用。為了實現這一點,我們需要一種方法讓子件在渲染時將數據傳遞給插槽。 我們可以將屬性從插槽傳遞出去,就像將資料傳遞`(props)`給組件一樣 ```template= <!-- <MyComponent> template --> <div> <slot :text="greetingMessage" :count="1"></slot> </div> ``` 使用不同的默認插槽與使用自定義插槽時接收道具有點不同v-slot ```template= <MyComponent v-slot="slotProps"> {{ slotProps.text }} {{ slotProps.count }} </MyComponent> ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up