vue-vant實現IndexBar索引欄


vant是一款基於vue的移動端組件庫,比如類似手機電話簿、城市的字母索引欄,下面介紹一下數據處理以及實現索引欄

1、效果圖如下:

2、數據格式化前后對比

格式化之前(即一般后台請求的數據)

格式化之后,將數據按開頭字母進行分類

3、數據格式化的方法

let cityName = {};
    //循環26個字母的數組
    this.FirstPin.forEach(item => {
    cityName[item] = [];
    cities.forEach(el => {
        //對比開頭字母是否對應
        let first = el.pinyin.substring(0, 1).toUpperCase();
        if (first == item) {
             cityName[item].push(el);
        }
     });            
});

4、全部實現代碼

<template>
    <div class="content">
        <van-sticky>
            <van-nav-bar
                title="選擇城市"
                left-arrow
            />
            <van-search v-model="search" placeholder="請輸入搜索關鍵詞" />
        </van-sticky>
        <van-index-bar :sticky='false'>
            <van-index-anchor :index="name" v-for="(item,name) in cities" :key="name">
                <b>{{name}}</b>
            </van-index-anchor>
        </van-index-bar>
    </div>
</template>

<script>
export default {
    data(){
        return{
            FirstPin: [
                "A",
                "B",
                "C",
                "D",
                "E",
                "F",
                "G",
                "H",
                "J",
                "K",
                "L",
                "M",
                "N",
                "P",
                "Q",
                "R",
                "S",
                "T",
                "W",
                "X",
                "Y",
                "Z"
            ],
            cities:{},
            search:''
        }
    },
    mounted(){
        this.$axios({
            url:'請求地址'
        }).then(res=>{
            var cities = '請求得到的數據';
            console.log(cities)
            let cityName = {};
            //循環26個字母的數組
            this.FirstPin.forEach(item => {
                cityName[item] = [];
                cities.forEach(el => {
                    //對比開頭字母是否對應
                    let first = el.pinyin.substring(0, 1).toUpperCase();
                    if (first == item) {
                        cityName[item].push(el);
                    }
                });            
            });
            console.log(cityName) 
            this.$nextTick(()=>{
                this.cities = cityName; 
            }) 
        }).catch(err=>{
            console.log(err)
        })
    }
}
</script>

<style lang="scss" scoped>
.content{
    background: #eee;
}
::v-deep .van-index-anchor{
    padding: 0;
    b{
        padding-left:10px;
        font-size: 14px;
        font-weight: 600;
    }
}
</style>
  學無止境,感興趣的話關注下面公眾號,咱們一起交流


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM