Practice accumulation - write a single line horizontal scroll component simply with vue3

Naughty snow fox 77 2021-08-09 16:27:15
practice accumulation write single line


Catalog

Copyright notice : This article is an original blog article , follow  CC 4.0 BY-SA  Copyright agreement , For reprint, please attach the original source link and this statement .

  • design sketch
  • Demand analysis
  • Implementation analysis

    • Style presentation analysis
    • Variable analysis
    • Methods to analyze
  • Implementation steps

      1. Implementation template
      1. Realization css
      1. First of all get list
      1. Listen after the page is mounted groupBoxRef Of scroll Event and get the current scroll position
      1. Calculate the width of the display , When the card width is greater than the outer width, it shows
      1. Controls the direction of the arrow display
      1. Monitor the change of outer layer width and window size, and the arrows are displayed and hidden
  • Complete code

design sketch

Take out a previously completed rendering and record it , The core code is here , If other technologies are used in the project , It's also easy to change .

Demand analysis

  1. Display data Always one line , The extra part can be scrolled out , Also hide the scroll bar style .
  2. Support notebook Touch slide Exhibition
  3. Support Click and slide the mouse , The arrow button appears when it is unnecessary , Default slide 3 The location of a card , The head switches direction
  4. When Listen when the page changes Show or hide buttons in time

Implementation analysis

Style presentation analysis

  • The outer layer controls the overall component width

    • The inner arrow area shows , For internal use flex Layout , Absolute positioning to the right

      • Internal arrow svg Icon , Vertical center
    • The inner layer controls the width of the scrolling area , For internal use flex Layout , Control the first floor display , Overflow scrolling display , And hide the scroll bar

      • Determine the width, height and spacing of the card inside , The last right margin is 0

    Variable analysis

  • card list:Array
  • Controls the visibility of arrows arrowShow:Boolean, Controls the direction of the arrow direction:String
  • Get scroll position scrollPosition = {left: 0, top: 0}
  • To calculate the width ref: Controls the scroll bar layer groupBoxRef, card groupCardRef

Methods to analyze

  1. obtain list( Sure http, It's fine too props, According to demand )
  2. After the page is mounted , monitor groupBoxRef Of scroll Events and window changes resize event
  3. Explicit and implicit judgment method of arrow , How to change the direction of the arrow
  4. The method of clicking the arrow with the mouse

Implementation steps

1. Implementation template

<template>
<div class="index-group-box">
<!-- Slide the arrow to the right -->
<div class="scrollX">
<img src='../assets/arrow-left-bold.svg'/>
</div>
<!-- card ⽚ -->
<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">
name
<span>{{ item.name }}</span>
</div>
</div>
</div>
</div>
</template>

2. Realization 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. First of all get list

<script>
import { defineComponent, ref } from 'vue';
export default defineComponent({
name: 'scroll',
setup() {
const groupInfo = ref([]);
// Get card list
const getMyGroup = async () => {
const data = [{
id: 1,
name:' card 1'
},{
id: 2,
name:' card 2'
},{
id: 3,
name:' card 3'
},{
id: 4,
name:' card 4'
},{
id: 5,
name:' card 5'
}]
groupInfo.value = data;
}
getMyGroup();
return {
// data
groupInfo,
};
},
});
</script>

4. Listen after the page is mounted groupBoxRef Of scroll Event and get the current scroll position

// add to reactive and onMounted
import { defineComponent, ref, reactive, onMounted }
...
const groupBoxRef = ref(null); // Get outer card ⽚ref
const groupCardRef = ref(null); // Get card ⽚ref
const scrollPosition = reactive({
left: 0,
top: 0
}); // Scroll position
...
// obtain scroll Position of function
const handleScroll = e => {
scrollPosition.left = e.target.scrollLeft;
scrollPosition.top = e.target.scrollTop;
}
getMyGroup();
onMounted(() => {
// monitor scroll event
groupBoxRef.value.addEventListener('scroll', handleScroll, true);
})
return {
// data
groupInfo,
// ref
groupBoxRef,
groupCardRef,
};

5. Calculate the width of the display , When the card width is greater than the outer width, it shows

  • Card width :groupCardRef.value.offsetWidth
  • Outer width :groupBoxRef.value.offsetWidth
  • Scroll area width : Number of cards * ( Card width + The right margin )- Last right margin
<div class="scrollX" v-if="arrowShow">
<img src='../assets/arrow-left-bold.svg'/>
</div>
...
const arrowShow = ref(false); // Whether the scroll arrow shows
// Get card ⽚ Width , The first ⼀ The first parameter is the card ⽚ Number , The default is the entire array , The first ⼆ The first parameter is the remaining margin
const getWidth = (num = groupInfo.value.length, restMargin = 16) => {
// If there is no content, return 0
if(!groupCardRef.value) return 0;
return num * (groupCardRef.value.offsetWidth + 16) - restMargin;
}
// Judge arrow Whether to show
const checkArrowShow = () => {
arrowShow.value = getWidth() > groupBoxRef.value?.offsetWidth ? true : false;
}
...
onMounted(() => {
// monitor scroll event
groupBoxRef.value.addEventListener('scroll', handleScroll, true);
// Check the arrow display for the first time
checkArrowShow();
})

6. Controls the direction of the arrow display

  • Initial right , The horizontal scroll area is 0 Just right , The remaining width is smaller than the outer width and faces to the left
  • Remaining width : Scroll area width - Rolling distance
<!-- Add click arrow events and arrow directions 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'); // The default items ⽬ Group arrow to the right
...
// Change scroll ⽅ towards
const changeArrow = (scrollLeft) => {
// Default get scoll Part of the entire width
const getScrollWidth = getWidth();
// Calculate the remaining width
const restWidth = getScrollWidth - scrollLeft
if (restWidth <= groupBoxRef.value.offsetWidth) {
direction.value = 'left'
} else if ( scrollLeft === 0 ) {
direction.value = 'right'
}
}
// ⿏ Click to scroll
const groupScroll = async () => {
// Calculate the moving width , Now it's mobile 3 Number of cards
const getMoveWidth = getWidth(3, 0);
// If the direction is to the right +, On the left -
if (direction.value === 'right') {
groupBoxRef.value.scrollLeft += getMoveWidth;
} else {
groupBoxRef.value.scrollLeft -= getMoveWidth;
}
// Scrolling takes time to get the latest distance , Look at the direction of the arrow according to the new distance
setTimeout(() => {
changeArrow(groupBoxRef.value.scrollLeft);
}, 500)
}
// When the touch panel slides, the position changes the arrow direction in real time
const handleScroll = e => {
...
changeArrow(scrollPosition.left);
}
return {
// Newly added data
...
direction,
// ref
...
// Newly added methods
groupScroll
};

7. Monitor the change of outer layer width and window size, and the arrows are displayed and hidden

import { defineComponent, ref, reactive, onMounted, watchEffect } from 'vue';
...
watchEffect(() => {
checkArrowShow();
})
onMounted(() => {
...
// Monitor window ⼝ Change events , Judge arrow The exhibition of
window.addEventListener('resize', checkArrowShow, true);
})

Complete code

<template>
<div class="index-group-box">
<!-- Slide the arrow to the right -->
<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>
<!-- card ⽚ -->
<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">
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([]); // card list
const direction = ref('right'); // The default arrow is to the right
const arrowShow = ref(false); // Whether the scroll arrow shows
const groupBoxRef = ref(null); // Get outer card ⽚ref
const groupCardRef = ref(null); // Get card ⽚ref
const scrollPosition = reactive({
left: 0,
top: 0
}); // Scroll position
// Get card list
const getMyGroup = async () => {
const data = [{
id: 1,
name:' card 1'
},{
id: 2,
name:' card 2'
},{
id: 3,
name:' card 3'
},{
id: 4,
name:' card 4'
},{
id: 5,
name:' card 5'
}]
groupInfo.value = data;
}
// Get card ⽚ Width , The first ⼀ The first parameter is the card ⽚ Number , The default is the entire array , The first ⼆ The first parameter is the remaining margin
const getWidth = (num = groupInfo.value.length, restMargin = 16) => {
// If there is no content, return 0
if(!groupCardRef.value) return 0;
return num * (groupCardRef.value.offsetWidth + 16) - restMargin;
}
// Change scroll ⽅ towards
const changeArrow = (scrollLeft) => {
// Default get scoll Part of the entire width
const getScrollWidth = getWidth();
// Get the remaining width
const restWidth = getScrollWidth - scrollLeft
if (restWidth <= groupBoxRef.value.offsetWidth) {
direction.value = 'left'
} else if ( scrollLeft === 0 ) {
direction.value = 'right'
}
}
// ⿏ Click to scroll
const groupScroll = async () => {
// Gets the scroll width
const getMoveWidth = getWidth(3, 0);
if (direction.value === 'right') {
groupBoxRef.value.scrollLeft += getMoveWidth;
} else {
groupBoxRef.value.scrollLeft -= getMoveWidth;
}
// Scrolling takes time to get the latest distance
setTimeout(() => {
changeArrow(groupBoxRef.value.scrollLeft);
}, 500)
}
// Judge arrow Whether to show
const checkArrowShow = () => {
arrowShow.value = getWidth() > groupBoxRef.value?.offsetWidth ? true : false;
}
watchEffect(() => {
checkArrowShow();
})
// obtain scroll Position of function
const handleScroll = e => {
scrollPosition.left = e.target.scrollLeft;
scrollPosition.top = e.target.scrollTop;
changeArrow(scrollPosition.left);
}
getMyGroup();
onMounted(() => {
// monitor scroll event
groupBoxRef.value.addEventListener('scroll', handleScroll, true);
// Monitor window ⼝ Change events , Judge arrow The exhibition of
window.addEventListener('resize', checkArrowShow, true);
// Check the arrow display for the first time
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>
版权声明
本文为[Naughty snow fox 77]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/08/20210809161751547J.html

  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