城市列表的json获取

  • axios的应用
  • 本地存储获取
  • 检查在本地存储内部有该值

axios是基于Promise的Http库;

window.localStorage.getItem(key) - 获取本地存储;

window.localStorage.setItem(key, value) - 将value的值存储到key中;

JSON.parse() -将json对象转换为JavaScript对象; 

JSON.stringify() -将JavaScript对象转换为JSON对象;

mounted(){
        var cityList = window.localStorage.getItem('cityList');
        var hotList = window.localStorage.getItem('hotList');
        //如果本地已经获取了缓存
        if(cityList && hotList){
            this.cityList = JSON.parse(cityList); //将字符串解析回json
            this.hotList = JSON.parse(hotList);
        }
        else{
            //否则使用axios获取api数据
            this.axios.get('/api/cityList').then((res) => {
               var msg = res.data.msg;
                if(msg === 'ok'){
                    var data = res.cities;
                    //使用一组对象获取被分类好的信息
                    var {cityList , hotList} = this.formatCityList(data);
                    this.cityList = cityList;
                    this.hotList = hotList;
                    window.localStorage.setItem('cityList' , JSON.stringify(cityList));
                    window.localStorage.setItem('hotList' , JSON.stringify(hotList));
                } 
            });
}
  • 循环获取api的数据进行筛选
  • A_Z分类,排序,首字母大写
function formatCityList(cities){
    var cityList = [];
    var hotList = [];

    for(let i=0; i<cities.length; i++){
        if(cities[i].isHot === 1){
            hotList.push(cities[i]);
        }
    }

    for(let i=0; i<cities.length; i++){
        var firstLetter = cities[i].py.substring(0,1).toUpperCase();
        if(toCom(firstLetter)){
            cityList.push({ index : firstLetter, list : [{ nm : cities[i].nm, id : cities[i].id }] });
        }
        else{
            for(var j=0; j<cityList.length; j++){
                if( cityList[j].index === firstLetter){
                    cityList[j].list.push({nm : cities[i].nm,  id : cities[i].id});
                }
            }
        }
    }


    //排序
    cityList.sort((n1, n2) => {
        if(n1.index > n2.index){
            return 1;
        }
        else if(n1.index < n2.index){
            return -1;
        }else{
            return 0;
        }
    });

    function toCom(firstLetter){
        for(let i = 0; i < cityList.length; i++){
            if( cityList[i].index === firstLetter ){
                return false;
            }
        }
        return true;
    }
}
发布了9 篇原创文章 · 获赞 0 · 访问量 3313

猜你喜欢

转载自blog.csdn.net/qq_27568213/article/details/104849098
今日推荐