在这节课的内容开始之前,我们先完善一下titleBar的内容,作为一个顶栏,一般都有一个返回按钮,用于返回上一页,现在就把顶栏的导航按钮做出来,正好也复习一下之前学的一些内容
<template>
<div class="title-bar">
<span class="back-icon" v-if="showBackBtn" @click="onBack"></span>
<div class="page-title">
<slot>未命名页面</slot>
</div>
</div>
</template>
<script>
export default {
props: {
showBackBtn: {
type: Boolean,
default: false,
},
},
methods: {
onBack() {
// 调用返回上一页的方法
this.$router.back()
},
},
}
</script>
<style scoped>
.title-bar {
width: 100%;
height: 64px;
background-color: #ccc;
position: relative;
}
.page-title {
position: absolute;
width: 100%;
line-height: 64px;
left: 0;
top: 0;
text-align: center;
}
.back-icon {
position: absolute;
width: 25px;
height: 25px;
border-left: 2px solid #333;
border-top: 2px solid #333;
transform: rotate(-45deg);
top: 17px;
left: 17px;
z-index: 1;
cursor: pointer;
}
</style>
在使用的时候,要传递showBackBtn为true,就可以显示返回按钮了
<title-bar :showBackBtn="true"></title-bar>
具名插槽
在标题栏中除了左侧有返回按钮,右侧也经常有一些功能按钮,
比如说,个人中心的入口,
比如说,在商品列表页筛选商品的按钮,
那么现在标题栏的右侧内容也得是动态插入进来,所以我们需要在titleBar里面写两个slot了,
为了区分两个或者多个slot,这时候就要顺其自然地给slot起个名字了,
具名插槽就是有名字的插槽,下面我们来给slot起名字
<template>
<div class="title-bar">
<span class="back-icon" v-if="showBackBtn" @click="onBack"></span>
<div class="page-title">
<slot name="title">未命名页面</slot>
</div>
<div class="right-content">
<slot name="rightContent"></slot>
</div>
</div>
</template>
起名字的方式也很直接,就是在slot这个标签上加一个name属性,那name的值就是它的名字了
<slot name="rightContent"></slot>
如果没有名字的话
<slot></slot>
这样的插槽它的名字默认是default,
但是为了大家阅读理解代码方便,在使用多个slot时一定要起名字,而且要起有意义,好理解的名字,
这样别人在读你的代码,或者时间久了以后自己再读的时候,比较容易理解
现在我们起好名字了,下面就是使用了
在App.vue中修改
<title-bar :showBackBtn="true">
<template v-slot:title>商品列表</template>
<template v-slot:rightContent>
<span>筛选</span>
</template>
</title-bar>
我们看到指定名字的语法是v-slot:加上在组件内定义好的名字,
v-slot:title
v-slot:rightContent
注意他们写在一个template标签上,template标签里的内容就会插入到相应的slot中
最后效果就是
具名插槽的简写
和v-on简写成@一样,v-slot也可以简写,v-slot:===>#,
上面的v-slot:title可以简写为#title
我们再次更改App.vue的内容
<title-bar :showBackBtn="true">
<template #title>商品列表</template>
<template #rightContent>
<span>筛选</span>
</template>
</title-bar>
效果也是一样的
这节课就到这里了,主要内容就是在有多个插槽时,给每个插槽起一个名字,在插入内容时,指定插槽的名字就行了