昨天用《VUE開發一個組件——Vue PC城市選擇控件》 , 有朋友說須要用字母篩選,其實已經用字母篩選了,不過是每4個,沒有對單個,因此H5咱們就用單個字母快速查找。javascript
和《VUE開發一個組件——Vue PC城市選擇控件》 同樣,可是不須要每4個再分組了。css
cityListData(){
let map = {};
let temps = [];
this.dataList.map(item=>{
if(item.airportCode){
let ekey = item.airportCode.charAt(0).toUpperCase();
temps = map[ekey] || [];
temps.push({
airportCode: item.airportCode,
airportName: item.cityName
});
map[ekey] = temps;
}
})
let list = [];
for(let gkey in map) {
list.push({
ckey: gkey,
cityList: map[gkey]
})
}
list = list.sort((li1, li2)=> li1.ckey.charCodeAt(0) - li2.ckey.charCodeAt(0));
return list;
},
cityListKey(){
let cityListKey = [];
this.cityListData.map(item=>{
cityListKey.push(item.ckey);
})
return cityListKey;
}
複製代碼
cityListData
整理後的數據,cityListKey
是全部字母。html
<div id="app">
<div class="city city-wap">
<div class="search">
<input type="text" placeholder="搜索條件">
</div>
<div class="city-list">
<div class="block-60"></div>
<div v-for="item in cityListData" class="clearfix">
<p :id="item.ckey">{{item.ckey}}</p>
<ul>
<li v-for="ritem in item.cityList">{{ritem.airportName}}</li>
</ul>
</div>
</div>
<div class="filter">
<div v-for="item in cityListKey" @click="switchKey(item)">{{item}}</div>
</div>
<div class="active-key" v-if="activeKey">{{activeKey}}</div>
</div>
</div>
複製代碼
search
沒有開發(用關鍵字搜索)、city-list
遍歷cityListData
、filter
篩選字母列表、active-key
提示當前選擇是那個字母。vue
.city-wap{
color: #3b4f62;
.clearfix{
&:after{
content: '';
display: block;
clear: both;
}
}
p{
background: #fff;
margin-bottom: 10px;
padding: 0 12px;
}
.search{
position: fixed;
top: 0;
box-shadow: 0 1px 3px 0 rgba(59,79,98,0.1);
width: 100%;
height: 50px;
input{
line-height: 50px;
width: 100%;
border: none;
box-shadow: none;
padding: 0 10px;
&:focus {
outline: none;
}
}
}
.city-list{
.block-60{
height: 60px;
}
ul{
padding: 0 10px;
li{
list-style: none;
display: inline-block;
margin-right: 10px;
width: 29%;
margin-bottom: 8px;
line-height: 35px;
text-align: center;
color: #333;
border-radius: 3px;
background: #fff;
font-size: 14px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding: 0 2px;
}
}
}
.filter{
position: fixed;
right: 3px;
top: 60px;
font-size: 15px;
div{
margin-top: 2px;
text-align: center;
}
}
.active-key{
position: fixed;
width: 100px;
height: 100px;
line-height: 100px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 100;
background: #dedede;
color: #fff;
border-radius: 100%;
text-align: center;
font-size: 40px;
}
}
複製代碼
這裏的.block-60
主要是用來佔位,否則城市會被上方的搜索框蓋住。java
switchKey(key){
// 當前選中的字母
this.activeKey = key;
// 1秒後清空,讓`active-key`隱藏
setTimeout(()=>{
this.activeKey = '';
}, 1000)
// 獲取當前字母來cityList中距離頂部的位置
let targetTop = document.querySelector('#'+key+'').offsetTop;
window.scrollTo({
top: targetTop - 60, // 60是search的高度
behavior: "smooth"
});
}
複製代碼
這樣就完工,是否是很簡單了?git
源碼地址:vue-c-citygithub
若是要PC<=>H5互換,須要修改main.js裏面的代碼。app