1、简单插槽<slot>标签可以将父组件传过来的标签内容显示在指定位置
<my-button>按钮</my-button>
let myButton = {
template: '<button><slot></slot></button>'
};
new Vue({
components: {
myButton
}
}).$mount('#app');
2、插槽内容除了简单文本还可以是html
<my-component>
<h1>标题1</h1>
<h2>标题2</h2>
</my-component>
let myComponent = {
template: '<div><slot></slot></div>'
};
new Vue({
components: {
myComponent
}
}).$mount('#app');
3、它甚至可以是其他组件
<my-component>
<h1>标题1</h1>
<h2>标题2</h2>
<my-component2></my-component2>
</my-component>
let myComponent = {
template: '<div><slot></slot></div>'
};
let myComponent2 = {
template: '<div>我是组件2</div>'
};
new Vue({
components: {
myComponent, myComponent2
}
}).$mount('#app');
4、默认值,我们可以给插槽指定默认值,当父组件没传入值是,显示默认值
let myComponent = {
template: '<div><slot>没传值时显示哥</slot></div>'
};
5、具名插槽,有时候我们希望传递多块内容,并将内容放在组件内的不同位置,这时候就可以使用具名插槽
<my-component>
<template v-slot:footer>页脚</template>
<template v-slot:main>内容</template>
<template v-slot:header>标题</template>
</my-component>
let myComponent = {
template: `<div>
<header><slot name="header"></slot></header>
<main><slot name="main"></slot></main>
<footer><slot name="footer"></slot></footer>
</div>`
};
new Vue({
components: {
myComponent
}
}).$mount('#app');
可以看到虽然header、main、footer的顺序是乱的,但是还是正确的显示在了指定的位置,如果插槽不指定名字,默认名字时default,没指定位置的插槽都将被显示在default的插槽中,如果组件中没有default插槽,那些没标记位置的内容将会被忽略。
6、作用域插槽,父组件调用子组件时是无法使用子组件中的数据作为插槽的内容的,但是有时候又有这样的需求,这时候可以使用插槽Props
<my-component>
<template v-slot:default="xxx">
{{xxx.users.username}}
</template>
</my-component>
let myComponent = {
template: `<div>
<slot v-bind:users="user">
</slot>
</div>`,
data(){
return {
user: {
username: '王五',
age: 18
}
}
}
};
new Vue({
components: {
myComponent
}
}).$mount('#app');