WXML 中
<view class="li l2"> <input id='searchInput' placeholder="請輸入企業全稱" type="text" bindinput="bindKeyInput" value="{{inputValue}}" data-statu="open" /> <view class="scrollview" wx:if="{{showInputStatus}}"> <view wx:for="{{bindSource}}"> <view id="{{item.id}}" data-name="{{item.name}}" class="itemview" bindtap="itemtap" data-statu="close" wx:if="{{showInputStatus}}">{{item.name}}</view> </view> </view> </view>
JS 中
data: { showInputStatus: false, //是否顯示匹配的數據 inpval: '', //雙向綁定輸入框 inputValue: '', //點擊結果項之后替換到文本框的值 selid: '', //點擊結果項之后選中的數據的id selname: '', //點擊結果項之后選中的數據的名稱 adapterSource: [], //本地匹配源 bindSource: [], //綁定到頁面的數據,根據用戶輸入動態變化 },
bindKeyInput: function (e) { console.log(e.detail.value) if (e.detail.value == null||e.detail.value =='') { this.setData({ showInputStatus:false }) return } if (e.detail.value !== undefined) { this.setData({ inpval: e.detail.value.replace(/\s+/g, '') }); } var currentInputStatu = e.currentTarget.dataset.statu; var prefix = e.detail.value.replace(/\s+/g, '') //用戶實時輸入值 var newSource = [] //匹配的結果 if (prefix != ""&&e.detail.keyCode) { // 調用接口,關鍵字返回匹配的數據列表 api.get(`/api/company/query-company?keyword=${prefix}`).then(res => { if (res.code == 200) { var arr = [] for (var i = 0; i < res.content.list.length; i++) { var obj = {} obj.name = res.content.list[i].companyName obj.id = res.content.list[i].userId arr.push(obj) } arr.forEach(function (e) { if (e.name.indexOf(prefix) != -1) { //返回某個指定的字符串值在字符串中首次出現的位置,如果要檢索的字符串值沒有出現,則該方法返回 -1 newSource.push(e) } }) if (newSource.length != 0) { this.setData({ bindSource: newSource }) } else { this.setData({ bindSource: [] }) currentInputStatu = "close"; } //關閉 if (currentInputStatu == "close") { this.setData({ showInputStatus: false }); } // 顯示 if (currentInputStatu == "open") { this.setData({ showInputStatus: true }); } } else { wx.showModal({ title: '提示', content: res.message, showCancel: false }) } }) } else { currentInputStatu = "close"; } },
itemtap: function (e) { var currentInputStatu = e.currentTarget.dataset.statu; var name = e.currentTarget.dataset.name; this.setData({ inputValue: name, selid: e.target.id, selname: name, inpval: name, bindSource: [] })//關閉 if (currentInputStatu == "close") { this.setData({ showInputStatus: false }); } // 顯示 if (currentInputStatu == "open") { this.setData({ showInputStatus: true }); } },