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>
posted @ 2020-08-20 09:51  飘逸_winxin  阅读(8939)  评论(2编辑  收藏  举报