- aplicaciones Axios
- Obtener el almacenamiento local
- El valor de comprobación dentro del almacenamiento local
axios se basa en la promesa de Http biblioteca;
window.localStorage.getItem (clave) - I Get a almacenamiento local;
window.localStorage.setItem (clave, valor) - el valor del valor almacenado en la clave;
JSON.parse () - objeto JSON en el objeto JavaScript;
JSON.stringify () - un objeto JavaScript en objeto 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));
}
});
}
- filtro de bucle de adquisición de datos Api
- A_Z clasificación, la clasificación, con mayúscula
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;
}
}