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

顽皮的雪狐七七 2021-08-09 16:17:54
前端 html5 javascript Vue.js CSS3


目录

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

  • 效果图
  • 需求分析
  • 实现分析

    • 样式展示分析
    • 变量分析
    • 方法分析
  • 实现步骤

      1. 实现模板
      1. 实现css
      1. 首先获取list
      1. 页面挂载后监听groupBoxRef的scroll事件并获取当前的滚动位置
      1. 计算展示的宽度显隐箭头,当卡片宽度大于外层宽度就展示
      1. 控制箭头展示方向
      1. 监听外层宽度改变和窗口大小改变箭头显隐
  • 完整代码

效果图

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

需求分析

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

实现分析

样式展示分析

  • 外层控制总体组件宽度

    • 内层箭头区域展示,内部使用flex布局,绝对定位到右侧

      • 内部箭头svg图标,垂直居中
    • 内层控制滚动区域宽度,内部使用flex布局,控制一层展示,溢出滚动展示,并隐藏滚动条

      • 内部确定卡片宽高和间距,最后一个右边距为0

    变量分析

  • 卡片 list:Array
  • 控制箭头显隐 arrowShow:Boolean,控制箭头方向 direction:String
  • 获取滚动位置 scrollPosition = {left: 0, top: 0}
  • 计算宽度需要的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',
setup() {
const groupInfo = ref([]);
// 获取卡片列表
const getMyGroup = async () => {
const data = [{
id: 1,
name:'卡片1'
},{
id: 2,
name:'卡片2'
},{
id: 3,
name:'卡片3'
},{
id: 4,
name:'卡片4'
},{
id: 5,
name:'卡片5'
}]
groupInfo.value = data;
}
getMyGroup();
return {
// data
groupInfo,
};
},
});
</script>

4. 页面挂载后监听groupBoxRef的scroll事件并获取当前的滚动位置

// 添加reactive和onMounted
import { defineComponent, ref, reactive, onMounted }
...
const groupBoxRef = ref(null); // 获取外层卡⽚ref
const groupCardRef = ref(null); // 获取卡⽚ref
const scrollPosition = reactive({
left: 0,
top: 0
}); // 滚动位置
...
// 获取scroll函数的位置
const handleScroll = e => {
scrollPosition.left = e.target.scrollLeft;
scrollPosition.top = e.target.scrollTop;
}
getMyGroup();
onMounted(() => {
// 监听scroll事件
groupBoxRef.value.addEventListener('scroll', handleScroll, true);
})
return {
// data
groupInfo,
// ref
groupBoxRef,
groupCardRef,
};

5. 计算展示的宽度显隐箭头,当卡片宽度大于外层宽度就展示

  • 卡片宽度:groupCardRef.value.offsetWidth
  • 外层宽度:groupBoxRef.value.offsetWidth
  • 滚动区域宽度:卡片数量 * (卡片宽度 + 右边距)- 最后一个右边距
<div class="scrollX" v-if="arrowShow">
<img src='../assets/arrow-left-bold.svg'/>
</div>
...
const arrowShow = ref(false); // 滚动箭头是否显示
// 获取卡⽚宽度,第⼀个参数是卡⽚个数,默认是整个数组,第⼆个参数是剩余的margin
const getWidth = (num = groupInfo.value.length, restMargin = 16) => {
// 如果没有内容就返回0
if(!groupCardRef.value) return 0;
return num * (groupCardRef.value.offsetWidth + 16) - restMargin;
}
// 判断arrow是否展示
const checkArrowShow = () => {
arrowShow.value = getWidth() > groupBoxRef.value?.offsetWidth ? true : false;
}
...
onMounted(() => {
// 监听scroll事件
groupBoxRef.value.addEventListener('scroll', handleScroll, true);
// 首次检查箭头展示
checkArrowShow();
})

6. 控制箭头展示方向

  • 初始朝右,横向滚动区域为0就朝右,剩余宽度比外层宽度小就朝左
  • 剩余宽度:滚动区域宽度 - 滚动距离
<!-- 添加点击箭头事件和箭头方向svg -->
<div class="scrollX" @click="groupScroll" v-if="arrowShow">
<img v-if="direction === 'left'" src='../assets/arrow-left-bold.svg'/>
<img v-else src='../assets/arrow-right-bold.svg'/>
</div>
...
const direction = ref('right'); // 默认项⽬组箭头向右
...
// 改变滚动⽅向
const changeArrow = (scrollLeft) => {
// 默认获取scoll部分整个宽度
const getScrollWidth = getWidth();
// 计算得出剩余宽度
const restWidth = getScrollWidth - scrollLeft
if (restWidth <= groupBoxRef.value.offsetWidth) {
direction.value = 'left'
} else if ( scrollLeft === 0 ) {
direction.value = 'right'
}
}
// ⿏标点击滚动
const groupScroll = async () => {
// 计算移动宽度,现在是移动3个卡片的数量
const getMoveWidth = getWidth(3, 0);
// 如果方向是右边就+,左边就-
if (direction.value === 'right') {
groupBoxRef.value.scrollLeft += getMoveWidth;
} else {
groupBoxRef.value.scrollLeft -= getMoveWidth;
}
// 滚动需要时间才能获取最新的距离,根据新的距离看箭头的方向
setTimeout(() => {
changeArrow(groupBoxRef.value.scrollLeft);
}, 500)
}
// 触摸板滑动的时候位置实时改变箭头方向
const handleScroll = e => {
...
changeArrow(scrollPosition.left);
}
return {
// 新加的data
...
direction,
// ref
...
// 新加的methods
groupScroll
};

7. 监听外层宽度改变和窗口大小改变箭头显隐

import { defineComponent, ref, reactive, onMounted, watchEffect } from 'vue';
...
watchEffect(() => {
checkArrowShow();
})
onMounted(() => {
...
// 监听窗⼝变化事件,判断arrow的展示
window.addEventListener('resize', checkArrowShow, true);
})

完整代码

<template>
<div class="index-group-box">
<!-- 右边滑动箭头 -->
<div class="scrollX" @click="groupScroll" v-if="arrowShow">
<img v-if="direction === 'left'" src='../assets/arrow-left-bold.svg'/>
<img v-else src='../assets/arrow-right-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>
<script>
import { defineComponent, ref, reactive, onMounted, watchEffect } from 'vue';
export default defineComponent({
name: 'scroll',
setup() {
const groupInfo = ref([]); // 卡片list
const direction = ref('right'); // 默认箭头向右
const arrowShow = ref(false); // 滚动箭头是否显示
const groupBoxRef = ref(null); // 获取外层卡⽚ref
const groupCardRef = ref(null); // 获取卡⽚ref
const scrollPosition = reactive({
left: 0,
top: 0
}); // 滚动位置
// 获取卡片列表
const getMyGroup = async () => {
const data = [{
id: 1,
name:'卡片1'
},{
id: 2,
name:'卡片2'
},{
id: 3,
name:'卡片3'
},{
id: 4,
name:'卡片4'
},{
id: 5,
name:'卡片5'
}]
groupInfo.value = data;
}
// 获取卡⽚宽度,第⼀个参数是卡⽚个数,默认是整个数组,第⼆个参数是剩余的margin
const getWidth = (num = groupInfo.value.length, restMargin = 16) => {
// 如果没有内容就返回0
if(!groupCardRef.value) return 0;
return num * (groupCardRef.value.offsetWidth + 16) - restMargin;
}
// 改变滚动⽅向
const changeArrow = (scrollLeft) => {
// 默认获取scoll部分整个宽度
const getScrollWidth = getWidth();
// 获取剩余宽度
const restWidth = getScrollWidth - scrollLeft
if (restWidth <= groupBoxRef.value.offsetWidth) {
direction.value = 'left'
} else if ( scrollLeft === 0 ) {
direction.value = 'right'
}
}
// ⿏标点击滚动
const groupScroll = async () => {
// 获取滚动宽度
const getMoveWidth = getWidth(3, 0);
if (direction.value === 'right') {
groupBoxRef.value.scrollLeft += getMoveWidth;
} else {
groupBoxRef.value.scrollLeft -= getMoveWidth;
}
// 滚动需要时间才能获取最新的距离
setTimeout(() => {
changeArrow(groupBoxRef.value.scrollLeft);
}, 500)
}
// 判断arrow是否展示
const checkArrowShow = () => {
arrowShow.value = getWidth() > groupBoxRef.value?.offsetWidth ? true : false;
}
watchEffect(() => {
checkArrowShow();
})
// 获取scroll函数的位置
const handleScroll = e => {
scrollPosition.left = e.target.scrollLeft;
scrollPosition.top = e.target.scrollTop;
changeArrow(scrollPosition.left);
}
getMyGroup();
onMounted(() => {
// 监听scroll事件
groupBoxRef.value.addEventListener('scroll', handleScroll, true);
// 监听窗⼝变化事件,判断arrow的展示
window.addEventListener('resize', checkArrowShow, true);
// 首次检查箭头展示
checkArrowShow();
})
return {
// data
groupInfo,
direction,
arrowShow,
// ref
groupBoxRef,
groupCardRef,
// methods
groupScroll
};
},
});
</script>
<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>
版权声明
本文为[顽皮的雪狐七七]所创,转载请带上原文链接,感谢
https://segmentfault.com/a/1190000040481137

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless