实践积累:用Vue3简单写一个单行横向滚动组件

效果图

把之前完成的一个效果图摘出来记录一下,核心代码在这里,如果项目中用到其他的技术,也很容易改。

scroll.gif

需求分析

  1. 展示数据始终一行,多余的部分可以出滚动条,同时隐藏滚动条样式。
  2. 支持笔记本触控滑动展示
  3. 支持鼠标点击滑动,多余的时候出现箭头按钮,默认滑动3个卡片的位置,顶头就切换方向
  4. 页面出现变动的时候要监听及时显示或隐藏按钮

实现分析

样式展示分析

  • 外层控制总体组件宽度
    • 内层箭头区域展示,内部使用flex布局,绝对定位到右侧
      • 内部箭头svg图标,垂直居中
    • 内层控制滚动区域宽度,内部使用flex布局,控制一层展示,溢出滚动展示,并隐藏滚动条
      • 内部确定卡片宽高和间距,最后一个右边距为0

变量分析

  1. 卡片 list:Array
  2. 控制箭头显隐 arrowShow:Boolean,控制箭头方向 direction:String
  3. 获取滚动位置 scrollPosition = {left: 0, top: 0}
  4. 计算宽度需要的ref:控制滚动条层 groupBoxRef,卡片 groupCardRef

方法分析

  1. 获取list(可以http,也可以props,根据需求来定)
  2. 页面挂载之后,监听groupBoxRef的scroll事件和窗口变化的resize事件
  3. 箭头的显隐判断方法,改变箭头方向的方法
  4. 鼠标点击箭头的方法

实现步骤

1. 实现模板

<template>
  <div class="index-group-box">
    <!-- 右边滑动箭头 -->
    <div class="scrollX">
      <img src='../assets/arrow-left-bold.svg'/>
    </div>
    <!-- 卡⽚ -->
    <div class="index-group-boxIn" ref="groupBoxRef">
      <div
        v-for="item in groupInfo"
        :key="item.id"
        ref="groupCardRef"
        class="group-card"
      >
        <div class="card-name">
          名称
          <span>{
   {
    item.name }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

2. 实现css

<style scoped>
  .index-group-box {
     
    padding-right: 16px;
    position: relative;
    box-sizing: border-box;
    width: 100%;
  }  

  .scrollX {
     
    width: 16px;
    position: absolute;
    top: 0;
    right: 0;
    height: 100%;
    background-color: #512D6D;
    display: flex;
    justify-content: center;
    align-items: center
  }

  .scrollX:hover {
     
    cursor: pointer;
    background-color: #65447d;
  }

  .index-group-boxIn {
     
    display: flex;
    scroll-behavior: smooth;
    white-space: nowrap;
    overflow-x: auto;
    flex: none;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE 10+ */
  }

  .index-group-boxIn::-webkit-scrollbar {
     
    display: none; /* Chrome Safari */
  }

  .group-card {
     
    padding: 8px 16px;
    box-sizing:border-box;
    width: 200px;
    height: 100px;
    border-radius: 4px;
    margin-right: 16px;
    flex: none;
    background: #71EFA3;
    color: #54436B;
  }

  .group-card span{
     
    color: #54436B;
  }

  .group-card:hover{
     
    background: #ACFFAD;
  }

  .group-card:nth-last-of-type(1){
     
    margin-right: 0px;
  }
</style>

3. 首先获取list

<script>
import {
    defineComponent, ref } from 'vue';
export default defineComponent({
   
    name: 'scroll'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值