插槽
- 父組件在參考子組件時希望向子組價傳遞模板內容;
- 子組件讓父組件傳過來的模板內容在所在的位置顯示;
- 子組件中的就是一個槽,可以接收父組件傳過來的模板內容, 元素自身將被替換;
- 用戶可以拓展組件,去更好地復用組件和對其做定制化處理,
默認插槽
<div id="app"></div>
Vue.component("TodoList", {
props:["list"],
methods: {
handleClick() {
this.count++;
},
},
data() {
return {
count: 0,
};
},
template: `<div>
<ul>
<li v-for="item in list">
<slot :item="item"></slot>
</li>
</ul>
</div>`,
});
app = new Vue({
el: `#app`,
template: `
<div>{{msg}}
<TodoList :list="list">
<template v-slot="{item}">
<span v-if="item.age == 18">*</span>
{{item.name}} -- {{item.age}}
</template>
</TodoList>
</div>`,
data: {
msg: "hello world",
list:[{
name:"xiaochen",
age:18
},{
name:"xiaohei",
age:90
}]
},
});

具名插槽和插槽作用域
Vue.component("ComponentA", {
methods: {
handleClick() {
this.count++;
},
},
data() {
return {
count: 0,
};
},
template: `<div>ComponentA
組件:{{count}}
<p><slot name="header" :count="count"></slot></p>
<p><slot></slot></p>
<p><slot name="footer"></slot></p>
<button @click="handleClick">click</button>
</div>`,
});
app = new Vue({
el: `#app`,
template: `
<div>{{msg}}
<ComponentA>
<template v-slot:header="data"> 插槽:{{data.count}}</template>
main
<template v-slot:footer>footer-spot</template>
</ComponentA>
</div>`,
data: {
msg: "hello world",
},
});

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/244368.html
標籤:其他
上一篇:瀏覽器端判斷當前設備的運行環境
