1.插槽的作用
当我们使用组件的时候,如果想让这个组件展示我们定制的内容,这个时候就需要插槽这个语法了。相当于把自己要展示的内容插入组件
2.普通插槽
const app = Vue.createApp({
data(){
return {
text: '提交'
}
},
template:
`
<test>
//这里是slot标签要展示的内容
//也就是插入test组件里面的内容
//这样就实现了展示内容定制的需求
<div>
{{text}}
</div>
</test>
`
});
app.component('test',{
// slot就是插槽
template: `<div><slot></slot></div>`
})
3.具名插槽
当我们的插槽想插在组件中的具体位置时,普通的插槽就显得不够用了。这个时候需要一种能标识位置的插槽,具名插槽应运而生,具名就是制定插槽的名字。
const app = Vue.createApp({
data() {
return {
text: "提交",
};
},
template: `
<layout>
//在template标签里面写名字
<template #header>
<div>header</div>
</template>
<template #footer>
<div >footer</div>
</template>
</layout>
`,
});
app.component("layout", {
template: `
<div>
//在这里指明放置哪个名字的内容
<slot name="header"></slot>
<div>content</div>
<slot name="footer"></slot>
</div>
`,
});
4.作用域插槽
当在将自己定制的组件插入时需要使用你插入的组件的数据时,就需要使用作用域插槽
const app = Vue.createApp({
data() {
return {
text: "提交",
};
},
template: `
//在这里用slotProps这个对象接收
<list v-slot="slotProps">
<span >{{slotProps.item}}</span>
</list>
`,
});
app.component("list", {
data() {
return { list: [1, 2, 3] };
},
template: `
<div>
//在这里将需要的数据传过去
<slot v-for="item in list" :item="item"/>
</div>
`,
});