WeChat applet scroll-view realizes left and right linkage

WeChat applet scroll-view realizes left and right linkage

This article shares the specific code for WeChat applet scroll-view to achieve left and right linkage for your reference. The specific content is as follows

Requirements: The project has a requirement for selecting cities, requiring that all provinces, cities and districts in the country be classified and sorted according to the first letter of the Chinese alphabet, and that the city list on the left and the letter list on the right be bidirectionally linked.

Step 1 : According to the interface provided by the javascript SDK provided by Tencent, obtain all provinces, cities and districts, and sort them by first letter.

let _this = this;
_this.mapCtx = wx.createMapContext("myMap");
        // Instantiate the API core class qqmapsdk = new QQMapWX({
            key: MAP_KEY,
        });
 
        // Get the national city list qqmapsdk.getCityList({
            success: function (res) {
                let list = res.result[0].concat(res.result[1], res.result[2]);
                _this.allCity = list;
                _this.cityList = _this.pySegSort(list);
            },
            fail: function (error) {
                console.error(error);
            },
            complete: function (res) {
                console.log(res);
            },
        });
 
        pySegSort(arr) {
            if (!String.prototype.localeCompare) return null;
            let letters = "*ABCDEFGHJKLMNOPQRSTWXYZ".split("");
            let zh = "This is a very simple and elegant sentence. I'm going to write it down here. I'm not ...
            let segs = [];
            let curr;
            letters.forEach(function (item, i) {
                curr = { letter: item, id: item, data: [] };
                arr.forEach(function (item2) {
                    if (
                        (!zh[i - 1] || zh[i - 1].localeCompare(item2.fullname) <= 0) &&
                        item2.fullname.localeCompare(zh[i]) == -1
                    ) {
                        curr.data.push(item2);
                    }
                });
                if (curr.data.length) {
                    curr.data.sort(function (a, b) {
                        return a.fullname.localeCompare(b.fullname);
                    });
                    segs.push(curr);
                }
            });
            return segs;
        },

Step 2: Calculate the height of the list consisting of each initial letter

When using query.selectAll('.cityList'), you should put it in setTimeout for asynchronous retrieval, otherwise the page has not been loaded yet and it cannot be retrieved. You can't get it even if you try to use $nextTick().

// Get the height of the popular city box let query = wx.createSelectorQuery().in(this);
        query
            .select(".hot-city")
            .boundingClientRect((data) => {
                this.hotCityHeight = data.height;
            })
            .exec();
 
        
        // Get the block height of each letter category setTimeout(() => {
            let query = wx.createSelectorQuery().in(this);
            query
                .selectAll(".cityList")
                .boundingClientRect((data) => {
                    console.log(data, "the height of each city classification");
                    this.letterBoxHeight = data;
                    this.heightArr = this.getHeight();
                })
                .exec();
        }, 1000); // Use setTimeout for asynchronous acquisition, otherwise it cannot be obtained // Calculate the height of each area getHeiht() {
            let n = this.hotCityHeight;
            let arr = [];
            this.letterBoxHeight.forEach((item) => {
                n = n + item.height;
 
                arr.push(n);
            });
            return arr;
        },

Step 3: Click on the right side to realize the linkage on the left side.

When you click on the letter list on the right, the city list on the left will scroll to the visible area. In this case, scroll-into-view="childViewId" is required.

// Click the letter on the right letterClick(letter, i) {
            this.letterIndex = i;
            this.currentIndex = i;
            this.childViewId = letter;
            setTimeout(() => {
                this.letterIndex = -1;
            }, 500); // The initial circle disappears after 0.5 seconds},

Step 4: Slide on the left and link the right sides.

When sliding the city list, you need to determine the current scroll height and the letter range within which the letters need to be highlighted.

calculateIndex(arr, scrollHeight) {
   let index = "";
   for (let i = 0; i < arr.length; i++) {
                if (scrollHeight >= this.hotCityHeight && scrollHeight < arr[0]) {
                    index = 0;
                } else if (scrollHeight >= arr[i - 1] && scrollHeight < arr[i]) {
                    index = i;
                }
            }
            return index;
        },
        // Calculate scroll distance scroll(e) {
            let scrollTop = e.detail.scrollTop;
            let scrollArr = this.heightArr;
            let index = this.calculateIndex(scrollArr, scrollTop);
            this.currentIndex = index;
        },

The completed code is as follows:

created() {
        let _this = this;
        _this.mapCtx = wx.createMapContext("myMap");
        // Instantiate the API core class qqmapsdk = new QQMapWX({
            key: MAP_KEY,
        });
 
        // Get the national city list qqmapsdk.getCityList({
            success: function (res) {
                let list = res.result[0].concat(res.result[1], res.result[2]);
                _this.allCity = list;
                _this.cityList = _this.pySegSort(list);
            },
            fail: function (error) {
                console.error(error);
            },
            complete: function (res) {
                console.log(res);
            },
        });
    },
    mounted() {
        // Get the height of the popular city box let query = wx.createSelectorQuery().in(this);
        query
            .select(".hot-city")
            .boundingClientRect((data) => {
                this.hotCityHeight = data.height;
            })
            .exec();
 
       
        // Get the block height of each letter category setTimeout(() => {
            let query = wx.createSelectorQuery().in(this);
            query
                .selectAll(".cityList")
                .boundingClientRect((data) => {
                    console.log(data, "the height of each city classification");
                    this.letterBoxHeight = data;
                    this.heightArr = this.getHeight();
                })
                .exec();
        }, 1000);
    },
    methods: {
        // Sort the city list alphabetically pySegSort(arr) {
            if (!String.prototype.localeCompare) return null;
            let letters = "*ABCDEFGHJKLMNOPQRSTWXYZ".split("");
            let zh = "This is a very simple and elegant sentence. I'm going to write it down here. I'm not ...
            let segs = [];
            let curr;
            letters.forEach(function (item, i) {
                curr = { letter: item, id: item, data: [] };
                arr.forEach(function (item2) {
                    if (
                        (!zh[i - 1] || zh[i - 1].localeCompare(item2.fullname) <= 0) &&
                        item2.fullname.localeCompare(zh[i]) == -1
                    ) {
                        curr.data.push(item2);
                    }
                });
                if (curr.data.length) {
                    curr.data.sort(function (a, b) {
                        return a.fullname.localeCompare(b.fullname);
                    });
                    segs.push(curr);
                }
            });
            return segs;
        },
        // Click the letter on the right letterClick(letter, i) {
            this.letterIndex = i;
            this.currentIndex = i;
            this.childViewId = letter;
            setTimeout(() => {
                this.letterIndex = -1;
            }, 500);
        },
        // Calculate the height of each area getHeiht() {
            let n = this.hotCityHeight;
            let arr = [];
            this.letterBoxHeight.forEach((item) => {
                n = n + item.height;
 
                arr.push(n);
            });
            return arr;
        },
        calculateIndex(arr, scrollHeight) {
            let index = "";
            for (let i = 0; i < arr.length; i++) {
                if (scrollHeight >= this.hotCityHeight && scrollHeight < arr[0]) {
                    index = 0;
                } else if (scrollHeight >= arr[i - 1] && scrollHeight < arr[i]) {
                    index = i;
                }
            }
            return index;
        },
        // Calculate scroll distance scroll(e) {
            let scrollTop = e.detail.scrollTop;
            let scrollArr = this.heightArr;
            let index = this.calculateIndex(scrollArr, scrollTop);
            this.currentIndex = index;
        },
}
<scroll-view scroll-y style="height: 1400rpx" :scroll-into-view="childViewId" @scroll="scroll">
            <!-- Popular Cities-->
            <view class="hot-city">
                <p>Popular cities</p>
                <ul>
                    <li
                        v-for="(item, idx) in hotCityList"
                        :key="idx"
                        :class="fixedPosition === item ? 'selected' : ''"
                        @click="selectCity(item)"
                    >
                        {{ item }}
                    </li>
                </ul>
            </view>
            <!-- Alphabetical list -->
            <view class="letterAz">
                <view
                    v-for="(item, idx) in letterAz"
                    :key="idx"
                    class="letter-item"
                    :class="currentIndex === idx ? 'selected' : ''"
                    @click="letterClick(item, idx)"
                >
                    {{ item }}
                    <view v-show="letterIndex === idx" class="pop-item">{{ item }}</view>
                </view>
            </view>
            <!-- List of cities -->
            <view v-for="(item, idx) in cityList" :key="idx" class="cityList">
                <view :id="item.id" class="city-letter">{{ item.letter }}</view>
                <view v-for="ele in item.data" :key="ele.id" class="city-name" @click="selectCity(ele.fullname)">{{
                    ele.fullname
                }}</view>
            </view>
</scroll-view>
// Popular cities.hot-city {
    padding: 38rpx 32rpx;
    p {
        font-size: 28rpx;
        line-height: 40rpx;
        color: #999999;
        margin-bottom: 32rpx;
    }
    ul {
        display: flex;
        flex-wrap: wrap;
        & li {
            background: rgba(0, 0, 0, 0.04);
            border-radius: 16rpx;
            font-size: 28rpx;
            color: #000000;
            text-align: center;
            margin: 8rpx;
            padding: 16rpx 46rpx;
        }
        & li.selected {
            background: rgba(45, 200, 77, 0.12);
            border: 0.66rpx solid #046a38;
            color: #046a38;
        }
    }
}
// Alphabet list.letterAz {
    position: fixed;
    right: 29rpx;
    top: 380rpx;
    font-size: 20rpx;
    line-height: 28rpx;
    color: rgba(0, 0, 0, 0.55);
    .letter-item {
        position: relative;
        margin-top: 4rpx;
        .pop-item {
            position: absolute;
            right: 165%;
            bottom: -100%;
            width: 96rpx;
            height: 96rpx;
            background: #ffffff;
            border: 0.66rpx solid rgba(0, 0, 0, 0.12);
            box-sizing: border-box;
            box-shadow: 0 10rpx 24rpx rgba(0, 0, 0, 0.08);
            border-radius: 100%;
            text-align: center;
            line-height: 96rpx;
            font-size: 40rpx;
            color: rgba(0, 0, 0, 0.85);
        }
    }
    .letter-item.selected {
        color: #046a38;
    }
}
// City List.cityList {
    margin-left: 32rpx;
    margin-right: 66rpx;
    margin-top: 20rpx;
    .city-letter {
        font-size: 28rpx;
        line-height: 40rpx;
        color: #999999;
    }
    .city-name {
        font-size: 28rpx;
        line-height: 40rpx;
        color: #000000;
        padding: 32rpx 0;
        border-bottom: 2rpx solid rgba(0, 0, 0, 0.12);
    }
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • WeChat applet realizes left-right linkage
  • WeChat applet realizes left-right linkage of menu
  • WeChat applet realizes left-right linkage of shopping pages
  • WeChat applet realizes the actual combat record of left and right linkage
  • WeChat applet scroll-view realizes left-right linkage effect

<<:  Implementation of Docker batch container orchestration

>>:  After idea publishes web project, Tomcat server cannot find the project and its solution

Recommend

Tutorial on installing rabbitmq using yum on centos8

Enter the /etc/yum.repos.d/ folder Create rabbitm...

Database SQL statement optimization

Why optimize: With the launch of the actual proje...

How to quickly modify the root password under CentOS8

Start the centos8 virtual machine and press the u...

MySQL's conceptual understanding of various locks

Optimistic Locking Optimistic locking is mostly i...

Steps to install MySQL 5.7.10 on Windows server 2008 r2

Install using the MSI installation package Downlo...

Detailed explanation of using Vue.prototype in Vue

Table of contents 1. Basic Example 2. Set the sco...

A brief introduction to bionic design in Internet web design

When it comes to bionic design, many people will t...

Recommend 60 paging cases and good practices

<br />Structure and hierarchy reduce complex...

100 ways to change the color of an image using CSS (worth collecting)

Preface “When it comes to image processing, we of...

About Nginx gzip configuration

The principle of nginx to achieve resource compre...