search
HomeWeb Front-endJS TutorialA brief discussion on how to implement the tab card switching function in mini programs

How does the mini program implement the tab card switching function? This article will introduce to you how to implement tab card switching in WeChat applet. I hope it will be helpful to you!

A brief discussion on how to implement the tab card switching function in mini programs

1. UI and interaction

First of all, let’s take a look at the UI appearance and interaction effect to be achieved. The picture below is One of our entrances. Clicking on each icon area below will display the corresponding card display.

A brief discussion on how to implement the tab card switching function in mini programs

For example, when I click on the icon of tab2, the corresponding jump will be as shown in the figure below.

The page is displayed as a long tab bar at the head, which can be slid left and right. Blank areas need to be left on both sides to achieve the centering effect of the tabs at both ends., click the corresponding tab The corresponding card can be displayed, , and the text of the tab will be displayed in the center. Similar to the effect of switching left and right carousels, I think as a user it should be easy to think of this kind of interaction.

The currently activated card will have an effect that feels slightly larger than other cards, and the edges of the front and back cards can be seen. And the card area can also be slid left and right to achieve the same interactive effect as the head tab bar.

This is probably such an interactive effect!

A brief discussion on how to implement the tab card switching function in mini programs

2. Design of the implementation plan

1. First of all, we need to know that all the tabs displayed on the front end are always displayed like this. Is it more than one, or is it possible that it will be expanded in the future, or that it is possible to iterate on it. I personally think we can discuss this with the back-end to unify the content we need to display into a set of constant configuration, and then we can make our dynamic rendering. Here I roughly maintain such a constant.

data: [
  {
    title: 'tab2', // 标题
    logoUrl: 'xxx', // 图标地址
    isNeed: false, // 是否需要该tab 
    id: '', // 每个tab对应的一个id,与后端交互使用
    content: '' // 每个tab对应的一些内容,用于扩展
    ...
  }
]

is roughly the above data structure.

2. When clicking the corresponding icon at the entrance, you can bring the corresponding array index or id into the details page to display the corresponding card And the corresponding ui

3. In the design of the details page, I divided the page into two components for display.

  • Header is the corresponding scroll-tab component. In this component, I used the component scroll-view provided by the WeChat applet. Here we need to set it## The #scroll-x parameter enables it to slide left and right. Setting the scroll-left parameter allows us to scroll to the middle when we click on a tab or slide the card. Content is the corresponding
  • swiper-card
  • component. In this component, I used the component swiper provided by the WeChat applet. Here we need to set it previous-margin and next-margin properties set the distance between the current card and the two cards before and after, current property sets the currently displayed card, bindchange event is used for card switching time interaction. In passing parameters on the index page, I choose to pass some corresponding data as well as
  • current value
  • and event processing function
    <view>
        <scroll-tab data="{{data}}" current="{{current}}" bind:chooseDetail="handleChooseDetail" />
        <swiper-card data="{{data}}" current="{{current}}" bind:swiperChange="handleSwiperChange" />
    </view>
  • 4. Specific implementation
  • 对于Header的tab栏两边留出可滑动的空间,因为scroll-view内部元素是无法占满该tab的宽度的,因此我们没有办法给其设置100%来实现。在这里我开始的想法是给其前后放置一个空白元素来给其宽度实现,后面参考了某个写法用了page-meta这个我也不太清楚是什么鬼的组件来设置左右的padding来实现,但是会有page-meta只用于页面首个节点的warning。对于两边距离的的设置,和scroll-left的设置,我采用了以下方法。
wx.getSystemInfo({
          success: res => {
            this.marginWidth = res.windowWidth / 2 // 两边空白距离
          }
        })
        
        
const computedPosition = (margin, textArr, preWidthArr) => {
  // margin每个tab之间的间距
  // textArr为所有tab的文字宽度的数组
  // preWidthArr为每一个tab与前一个tab的距离数组,第一个默认为0
  let distanceArr = []
  let len = textArr?.length
  for (let i = 0; i < textArr?.length; i++) {
    distanceArr.unshift(preWidthArr[len - 1] + (len - 1) * margin + textArr[len - 1] / 2)
    len--
  }
  // distanceArr为每个tab居中展示时应该设置的scroll-left值
  return distanceArr
}

// textArr[n] = 第 n - 1元素的宽度
// const widthArr = [78, 78, 78, 52, 52, 52]

// preWidthArr[n] = 第n - 1个tab距离前面tab的距离 = 元素宽 + margin
// 第一个tab没有前面的元素
// const arr = [0, 78, 156, 234, 286, 338]

// 获取元素信息
getElementAttr() {
        wx.createSelectorQuery()
          .in(this)
          .selectAll(&#39;.swiper-text__item&#39;)
          .boundingClientRect(res => {
            const textWidth = res?.map(item => item.width)
            const preWidth = this.getPreWidth(textWidth)
            this.distanceArr = computedPosition(MARGIN, textWidth, preWidth)
          })
          .exec()
},
getPreWidth(textWidth) {
        const arr = [0]
        for (let i = 0; i < textWidth.length - 1; i++) {
          arr.push(textWidth[i] + arr[i])
        }
        return arr
}
  • 对于Content内容区域的卡片,可以给当前卡片与别的卡片设置不同的transfrom: scale(倍数),并且给一个过渡效果transition即可实现简单的交互效果。

三、大功告成,开始复盘

  • scroll-view的scroll-left曾经踩过不生效的
  • scroll-view的内容区域并不能撑满宽度100%
  • 如何根据不同tab文字的宽度来设置对应的scroll-left距离
  • 如何实现左右两边留出可滑动区域
  • 如何做出更顺畅更友好的交互效果

写在最后

前段时间接了这个需求的时候我作为owner,和一个同事为该需求评估排期时间时评的是10人日,我自然而然的也想尝试一下所以选择了ui与交互更为复杂的内容,当然以上要实现的内容只是其中一个部分,说实话在实现过程中我真的挺痛苦的,还有一个半圆弧状的进度条展示,首尾都要有弧度的那一种,作为一个应届小白,还是有太多不会的东西了,即使是这些在他们眼里看作为很简单的内容,一下就能实现的内容,在我这里可要经历太多了,我知道我菜,但我会继续努力,作为一个前端开发,高还原度实现ui设计稿一直作为我的初衷。但希望你们不要以这个我xxx(多久时间)就能做出来的口吻来pua我,至少我认为在几年后我会比你们更加优秀,但一定不会用这样的口吻来对待我的应届同事们。

【相关学习推荐:小程序开发教程

The above is the detailed content of A brief discussion on how to implement the tab card switching function in mini programs. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),