First, component origin

1. The demand

Recently, AT the request of the development team leader and product manager, I wrote several H5 activity pages in succession. In hindsight, it turns out that all of these activities have a few things in common: they all have a navigation Tab. Click a TAB, send a request, and switch between content.At that time, because the project was launched in a hurry, only one day, the product and development team leader required that TAB could slide, and no animation was needed, so it was very simple: Wrap the container around a number of children, make them horizontal, and then the parent container hides the horizontal scroll bar, and the user can only slide left and right, and then click on a TAB, and the TAB background is highlighted.

Problem 2.

The TAB bar works, but there is a problem: if the user clicks on a TAB, the TAB is highlighted, and then slides the entire TAB bar, the highlighted TAB is not known, as shown below:Although the problem was discovered, it was not resolved due to time constraints and heavy tasks. During a weekly meeting, the product asked this question, expecting the user to always hit TAB to roll to the center.

Two, component writing

1. The train of thought

Without further ado, the original address of the code is attached: github.com/Mryuelaiyue… The core problem is: how to calculate the distance between the Swipe and Popup of the current TAB item? After thinking for some time, I finally get the result, and attach the code block and image

  this.$refs.tabItemWrap[i].offsetLeft + // Activate offsetLeft for the TAB child
        this.tabItemWrapWidth / 2 -      // Wrap the width of the subtab item /2
        this.tabWidth / 2 -              // The width of the TAB column
        this.$refs.tab.offsetLeft -      // TAB column offsetLeft
        this.wrapPaddingRight / 2        // The right margin inside the container surrounding the child TAB is /2
Copy the code

> > < span style = “box-sizing: border-box; color: RGB (74, 74, 74); color: RGB (74, 74, 74); line-height: 20px; font-size: 14px! Important; white-space: normal; white-space: normal; line-height: 20px! Important;” To get the exact value, we need to use getBoundingClientRect().width. From there, everything is easy: just roll the current TAB bar to this location. For a more comfortable look, I introduced the animate library, which looks like 🎉🎉🎉

If you have any problems, please comment and correct them