跟着coderwhy老师学做tabbar,效果如图:
按照coderwhy老师的代码敲,发现底下的导航栏图标、文字都不显示!
原来是因为我创建的项目是Vue3,而coderwhy老师的是Vue2。
Vue3、Vue2对插槽slot的使用有区别!
App.vue文件中使用了TabBar组件,TabBar组件内有匿名插槽,TabBar组件插槽中插入,TabBarItem组件,TabBarItem组件内有两个具名插槽。(下面代码<tab-bar-item>中空的几行,Vue3、Vue2写法不同,故空着先,后面再讲怎么写)
<!-- App.vue -->
<template>
<div id="app">
<tab-bar>
<tab-bar-item>
<!-- todo -->
</tab-bar-item>
</tab-bar>
</div>
</template>
<!-- TabBar.vue -->
<template>
<div id="tab-bar">
<slot></slot>
</div>
</template>
<!-- TabBarItem.vue -->
<template>
<div class="tab-bar-item">
<slot name="item-icon"></slot>
<slot name="item-text"></slot>
</div>
</template>
Vue2的项目写法为(coderwhy老师的写法):
<tab-bar-item>
<img src="./assets/img/tabbar/home.svg" slot="item-icon" alt="">
<div slot="item-text">首页</div>
</tab-bar-item>
但是我这么写,不显示图标、文字,底下的导航栏为空。
能正常显示的写法(Vue3写法):
<tab-bar-item>
<template v-slot:item-icon>
<img src="./assets/img/tabbar/home.svg" alt="">
</template>
<template v-slot:item-text>
<div slot="text">首页</div>
</template>
</tab-bar-item>
⚠️ 要用template包住! 用 v-slot 代替 Vue2 的 slot !
但是发现,这样写以后,在 TabBarItem.vue 中的写样式(限制图标、文字大小),并不奏效!
Vue2项目,将 TabBarItem 的样式写在 TabBarItem.vue 中:
<style scoped>
.tab-bar-item {
flex: 1;
text-align: center;
height: 49px;
font-size: 10px;
}
.tab-bar-item img{
height: 24px;
margin-top: 3px;
/*去除图片底部默认添加的3个像素*/
vertical-align: middle;
}
</style>
coderwhy老师替换插槽,有效果。
但是我没有效果,我以为是Vue3不能用原来组件的样式,于是复制了一份到App.vue 里。
结果是!!要把TabBarItem.vue 中的 style 的scoped 去掉!!
解决问题!