Vue3与Vue2插槽slot的使用区别,Vue3插槽样式

跟着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 去掉!!

解决问题!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值