上篇提到slot傳入的內容都是由外層元件提供,如果內層元件slot也想使用內層資料時,就可以使用Slot Props,概念就是內層元件利用插槽的props將部份內層資料,傳遞給外層元件做使用。
Slot Props參考以下程式碼:
<div id="app">
<out-text>
<template v-slot:default="roprops">
內層元件插槽:
{{ roprops.ro.name }}
</template>
</out-text>
</div>
const app = Vue.createApp({
data() {
return {
text: "外層元件",
}
}
});
app.component("outText",{
template: `
<div class="header">
<slot :ro="product"></slot>
</div>
`,
data() {
return {
text: "內部元件",
product: {
name: "名刀不知火",
price: 200000,
city: "普隆德拉"
}
};
}
});
app.mount("#app");
<slot :ro="product"></slot>,:ro為自定義名稱,product為內層元件的data。v-slot:default="roprops"接收資料,v-slot:default固定寫法,roprops為自定義名稱。Slot Props搭配Component Props<div id="app">
<out-text :product="product">
<template v-slot:default="{ ro, buy }">
component props:{{ ro.name }} <br>
slot props:{{ buy }}
</template>
</out-text>
</div>
const app = Vue.createApp({
data() {
return {
text: "外層元件",
product: {
name: "名刀不知火",
price: 200000,
city: "普隆德拉",
amount: 5,
}
}
}
});
app.component("outText",{
props: ['product'],
template: `
<div class="header">
<slot :ro="product" :buy="buy"></slot>
</div>
`,
data() {
return {
text: "內部元件",
buy: ""
};
},
created() {
if(this.product.amount > 1 ){
this.buy = "可購買";
}else {
this.buy = "無法購買";
};
}
});
app.mount("#app");
props到子元件使用,<out-text :product="product">,props: ['product']。mounted()。<slot :ro="product" :buy="buy"></slot>(資料是外部元件data,經由內部元件props提供)。v-slot:default="{ ro, buy }"。外層模板改為物件方式接收v-slot:default="{ ro, buy }"
我"猜"這邊應該是用到解構賦值(Destructuring Assignment)