插槽
默认情况下,组件模板解析后会替换整个组件内容,如果我们想在组件引用被包含的内容,可以通过 vue
提供的内置组件 slot
来获取
.dialog {
position: fixed;
left: 50%;
top: 30%;
transform: translateX(-50%) translateY(-50%) ;
border-radius: 2px;
box-shadow: 0 1px 3px rgba(0,0,0,.3);
box-sizing: border-box;
background: #fff;
width: 30%;
}
.dialog_header {
padding: 20px 20px 0;
text-align: left;
}
.dialog_title {
font-size: 16px;
font-weight: 700;
color: #1f2d3d;
}
.dialog_content {
padding: 30px 20px;
color: #48576a;
font-size: 14px;
text-align: left;
}
.dialog_close_btn {
position: absolute;
right: 10px;
top: 5px;
}
.dialog_close_btn:before {
content: 'x';
color: #999;
font-size: 20px;
cursor: pointer;
}
<div id="app">
<kkb-dialog title="标题">
<p>这是内容</p>
</kkb-dialog>
</div>
const Dialog = {
props: ['title'],
template: `
<div class="dialog">
<i class="dialog_close_btn"></i>
<div class="dialog_header">
<span class="dialog_title">{{title}}</span>
</div>
<div class="dialog_content">
<slot></slot>
</div>
</div>
`
};
new Vue({
el: '#app',
components: {
'kkb-dialog': Dialog
}
});
具名插槽
<div id="app">
<kkb-dialog>
<template v-slot:title>
<h1>这是标题</h1>
</template>
<template v-slot:default>
<p>这是内容</p>
</template>
</kkb-dialog>
</div>
const Dialog = {
props: ['title'],
template: `
<div class="dialog">
<i class="dialog_close_btn"></i>
<div class="dialog_header">
<slot name="title"></slot>
</div>
<div class="dialog_content">
<slot></slot>
</div>
</div>
`
};
new Vue({
el: '#app',
components: {
'kkb-dialog': Dialog
}
});
v-slot
使用内置组件 template
与 v-slot
指令进行配置,用来命名插槽,在组件模板中,通过 <slot name="插槽名字">
来使用
作用域插槽
组件内部与组件包含的内容属于不同的作用域(被包含的内容是组件父级下的作用域)
<div id="app">
<kkb-dialog>
<template v-slot:title>
<h1>用户列表 - {{title}}</h1>
</template>
<template v-slot:default="data">
<p>用户的姓名: {{data.user.username}}</p>
</template>
</kkb-dialog>
</div>
const Dialog = {
props: ['title'],
data() {
return {
users: [
{id: 1, username: 'baogege', gender: '男',checked:false},
{id: 2, username: 'mt', gender: '男',checked:false},
{id: 3, username: 'haigege', gender: '男',checked:false},
{id: 4, username: 'zMouse', gender: '男',checked:false},
{id: 5, username: 'reci', gender: '女',checked:false},
{id: 6, username: 'lisi', gender: '女',checked:false}
]
}
},
template: `
<div class="dialog">
<i class="dialog_close_btn"></i>
<div class="dialog_header">
<slot name="title"></slot>
</div>
<div class="dialog_content">
<slot v-for="user of users" :user="user"></slot>
</div>
</div>
`
};
new Vue({
el: '#app',
data: {
title: '开课吧'
},
components: {
'kkb-dialog': Dialog
}
});