由于之前开发的大数据项目(vue)中有使用到slot,当时是为了完成项目进度,在网上找的做好的组件直接使用的,并不懂slot的用法,最近趁着没有项目发开任务,重新学了一下vue slot的相关内容,目前学的比较浅,希望之后能后作出一些小demo。
项目实例
项目层级关系:入口为home.vue,并且为父组件,子组件为Testslot.vue,其中子组件用来完成模板,父组件用来调用子组件并显示。
//子组件Testslot.vue
<template>
<div class="panel">
<div class="title">这是头部</div>
<div class="content">这是中间的内容</div>
<div class="footer">这是尾部</div>
</div>
</template>
<style scoped>
.panel{
max-width: 300px;
border: 1px solid #999;
padding: 15px;
}
.panel .title{
border-bottom: 1px solid #999;
}
.panel .footer{
border-top: 1px solid #999;
}
</style>
//父组件home.vue
<template>
<div>
<panel></panel>
<panel></panel>
<panel></panel>
</div>
</template>
<script>
import Testslot from './Testslot.vue';
export default {
components: {
'panel':Testslot
},
}
</script>
此时代码的效果如图

此时的效果是有三个自己定义的panel,三个里面的内容全都一样,现在想要让模板里面的content的内容可以自己定义,其他的地方不变,这就需要使用到slot,代码如下。
//子组件Testslot.vue
<template>
<div class="panel">
<div class="title">这是头部</div>
<div class="content">
<slot></slot>
</div>
<div class="footer">这是尾部</div>
</div>
</template>
<style scoped>
.panel{
max-width: 300px;
border: 1px solid #999;
padding: 15px;
}
.panel .title{
border-bottom: 1px solid #999;
}
.panel .footer{
border-top: 1px solid #999;
}
</style>
//父组件home.vue
<template>
<div>
<panel>123</panel>
<panel>456</panel>
<panel>789</panel>
</div>
</template>
<script>
import Testslot from './Testslot.vue';
export default {
components: {
'panel':Testslot
},
}
</script>
此时的效果如下图

这就通过匿名插槽实现了自定义模板的内容,而什么是具名插槽呢,就是我现在不止想要content的内容也已自定义,我想把title和footer都通过slot变成自定义的,但是我在父组件中调用panel的时候,怎么那个panel知道哪些文字是放在title的,哪些文字是放在content的,哪些文字是放在footer的呢??!!代码如下:
//子组件Testslot.vue
<template>
<div class="panel">
<div class="title">
<slot name="title"></slot>
</div>
<div class="content">
<slot name="content"></slot>
</div>
<div class="footer">
<slot name="footer"></slot>
</div>
</div>
</template>
<style scoped>
.panel{
max-width: 300px;
border: 1px solid #999;
padding: 15px;
}
.panel .title{
border-bottom: 1px solid #999;
}
.panel .footer{
border-top: 1px solid #999;
}
</style>
//父组件home.vue
<template>
<div>
<panel>
<div slot="title">title1</div>
<div slot="content">content1</div>
<div slot="footer">footer1</div>
</panel>
<panel>
<div slot="title">title2</div>
<div slot="content">content2</div>
<div slot="footer">footer2</div>
</panel>
</div>
</template>
<script>
import Testslot from './Testslot.vue';
export default {
components: {
'panel':Testslot
},
}
</script>
效果如下

好啦!!以上就是我对匿名插槽和具名插槽的理解,希望对你也有帮助哟~
网友评论