最近做項目中,碰到了點小麻煩:
后台從接口請求回來的城市相關的數據只有城市名稱,沒有排序,鋪頁面的時候要排序就很麻煩;
面向百度編程時候找到了一個包,用它來將字符串轉成拼音,就可以通過字符串截取取出拼音首字母,這樣就可以進行首字母排序了。
這個包的名字叫js-pinyin。
- npm下載
npm i js-pinyin
- 下載完了之后在main.js中引入
import pinyin from 'js-pinyin'
這樣使用環境就配置好了。
當在組件中使用時,要先在export default前引用node_modules/js-pinyin中的index.js文件:
import pinyin from '../../../node_modules/js-pinyin/index'
注意node_modules/js-pinyin的文件路徑
因為我要在頁面加載時就使用這個需要排序的數據,所以我將代碼寫入mounted()中。
在使用真實數據前,我們先寫一個小demo:
在組件中使用時,要添加
let pinyin = require('js-pinyin');
和
pinyin.setOptions({checkPolyphone: false, charCase: 0});
兩行代碼,一個是引入js-pinyin,一個是配置js-pinyin。
完整的demo就是這樣:
mounted() {
let pinyin = require('js-pinyin');
pinyin.setOptions({checkPolyphone: false, charCase: 0});
console.log(pinyin.getFullChars('管理員')); //GuanLiYuan
console.log(pinyin.getCamelChars('管理員')); //GLY
console.log(pinyin.getCamelChars('1234')); //1234
console.log(pinyin.getCamelChars('english')); //english
}
上述2個console.log中使用的函數,是js-pinyin中設計好的2個函數,作用分別是:
- getFullChars():獲取字符串全部拼音,並且首字母大寫;
- getCamelChars() : 獲取字符串拼音首字母,並大寫;
getCamelChars()中傳入的參數不是漢字時,不會進行轉換,仍然輸出源字符串。
接下來使用真實數據:
首先后台給我請求回來的數據結構是這個樣子的:

我需要使用js-pinyin給請求回來的數據添加一個“first: 首字母”鍵值對,用來標識首字母。
data() {
return {
FristPin: ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"],
cityjson: {},
}
},
mounted() {
let pinyin = require('js-pinyin');
pinyin.setOptions({checkPolyphone: false, charCase: 0});
//先拿到全部城市的名字
let cityArr = [];
index.tools.getAllCity().then(res => { //這是axios請求,請求回來的結果是res
for (let i = 0; i < res.data.city.length; i++) {
//遍歷數組,拿到城市名稱
let cityName = res.data.city[i].name;
//取全部城市的首字母
let fristName = pinyin.getCamelChars(cityName).substring(0, 1); //這里截取首字母的第一位
//給原json添加首字母鍵值對
res.data.city[i].first = fristName;
//放入新數組
cityArr.push(res.data.city[i]);
}
let cityJson = {};
//根據首字母鍵值對給原數據按首字母分類
for (let i = 0; i < _this.FristPin.length; i++) { //這里的FirstPin是一個寫入了所有字母的數組,見data中
cityJson[_this.FristPin[i]] = cityArr.filter(function (value) {
return value.first === _this.FristPin[i];
})
}
_this.cityjson = cityJson;
}
});
最后請求回來的數據經過我們處理后變成了data中的this.cityjson,就是以首字母開頭的結構了。



