Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
Requirements:
Usually when doing projects, there will be a large number of address list information (such as high-speed railway station, airport station and geographical location) in the selection list of addresses. Therefore, an index bar on the right side is required to play a role in screening and classification. On mobile, IndexBar, IndexAnchor and JS-Pinyin packages in Vuant-UI are generally used.
1. Installation:
npm install js-pinyin
2. Use:
With IndexBar in Vuant-UI, IndexAnchor uses plugins to install IndexAnchor on pages that need to be used:
import pinyin from “js-pinyin”;
After the interface is called, the region list data is obtained, and each piece of data is traversed. The pinyin.getCamelchars () method is called to transform the first letter of each city to get a list of first letters
i.acronym = pinyin
.getCamelChars(i.airportName)
.substr(0, 1)
.toLocaleUpperCase();
charList.push(i.acronym);
return i;
});
airCharList = Array.from(new Set(charList)).sort();
Copy the code
Assign the first letter of the list data to van-index-bar’s indexList
:index-list="airCharList"
:sticky-offset-top="stickyOffsetTop"
>
<view v-for="item in airTrainList" :key="item.acr">
<van-index-anchor :index="item.acr" />
<view
class="city-item"
v-for="(air, index) in item.list"
:key="index"
@click="checkAirTrain(air)"
>{{ air.airportName }}</view
>
</view>
</van-index-bar>
Copy the code
At the same time, the original list data should be adjusted to make the list order consistent with the character order, that is, according to the first letter “A, B,C,D…” In this order
charList.forEach((char) => { let obj = {}; let list = []; arrList.forEach((i) => { if (char == i.acronym) { list.push(i); }}); obj.acr = char; obj.list = list; airAllList.push(obj); }); this.airTrainList = airAllList; this.airCharList = charList;Copy the code
Js-pinyin method extension:
Console. log(pinyin.getFullchars (‘ admin ‘)) //GuanLiYuan; Console. log(pinyin.getCamelchars (‘ admin ‘)) //GLY; console.log(pinyin.getCamelChars(‘1234’)) //1234; The console. The log (pinyin. GetCamelChars (‘ tube ‘)) / / G;