uni-app小程序,实现根据中文首字母排序功能
描述:
從后端調用接口獲取所有熱的姓名,將這些名字的首字母排序,然后放到對應字母下面,最終效果圖如下:
實現過程
**總體實現的思路是:**首先調用接口,獲取所有員工的姓名以及其他信息,將獲取回來的中文名字轉換為拼音,這里做的是轉為姓名首字母大寫的簡寫格式(比如:“張三” 轉為“ZS”)這里只需要名字的第一個字的首字母,使用js的截取功能就能實現,中文轉拼音這里我使用的是js-pinyin,將轉換好的內容渲染到頁面上。
1、下載js-pinyin包
npm install js-pinyin
2、在main.js中引入js-pinyin
import pinyin from 'js-pinyin'
3、在methdos函數中調用接口獲取名字的數據,這里的res就是獲取回來的員工信息。獲取回來的數據結構如下圖
4、實現中文轉換為拼音的功能
(1)、當在組件中使用時,要先在export default前引用node_modules/js-pinyin中的index.js文件:
import pinyin from '…/…/…/node_modules/js-pinyin/index
注意node_modules/js-pinyin的文件路徑
(2)、一個是引入js-pinyin,一個是配置js-pinyin。
let pinyin = require('js-pinyin') pinyin.setOptions({checkPolyphone: false, charCase: 0})(3)、在data中定義變量
data(){return{firstPin :["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"],namejson:{},//轉換為拼音后的數據} }(4)、獲取姓名,將其轉為拼音
//循環數組,拿到所有的姓名 for(var i = 0 ; i < res.data.content.length ; i ++){ // 取所有姓名的首字母let peopleName = res.data.content[i].name// 取所有姓名的首字母let firstname = pinyin.getCamelChars(peopleName).substring(0, 1)//給原json添加首字母鍵值對res.data.content[i].first = firstname//放入新數組nameArr.push(res.data.content[i])// that.result.push(res.data.content[i].id) }(5)、整理完后的數據格式如下圖:
轉換為拼音的所有代碼如下:
getData(){let nameArr = [];var that = thisuni.request({url: '獲取員工信息的接口', data: {id:that.id,repairType:that.repairType},method:'POST',header: {'content-type': 'application/x-www-form-urlencoded','Cookie': 'JSESSIONID=' + uni.getStorageSync('token')},dataType:'json',success: (res) => {console.log("選擇員工的數據")console.log(res)let dataArr = res.data.contentlet pinyin = require('js-pinyin')pinyin.setOptions({checkPolyphone: false, charCase: 0})//循環數組,拿到所有的姓名for(var i = 0 ; i < res.data.content.length ; i ++){// 取所有姓名的首字母let peopleName = res.data.content[i].name// 取所有姓名的首字母let firstname = pinyin.getCamelChars(peopleName).substring(0, 1)//給原json添加首字母鍵值對res.data.content[i].first = firstname//放入新數組nameArr.push(res.data.content[i])// that.result.push(res.data.content[i].id)}console.log(that.result)let namejson = {};//根據首字母鍵值對給原數據按首字母分類for (let i = 0; i < that.firstPin.length; i++) { //這里的FirstPin是一個寫入了所有字母的數組,見data中namejson[that.firstPin[i]] = nameArr.filter(function (value) {return value.first === that.firstPin[i]})}that.namejson = namejsonconsole.log(that.namejson)console.log(that.namejson.Z )}})},前端頁面渲染
1、前端布局
這里的布局使用的是van -weapp組件庫的van-index-bar、van-index-ancho組件。
參考文章:
https://www.cnblogs.com/lzb1234/p/11353152.html
總結
以上是生活随笔為你收集整理的uni-app小程序,实现根据中文首字母排序功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为自己的梦想而奋斗
- 下一篇: facebook女程序员_Faceboo