最近做的頁面跟UI溝通過以后希望在下拉框上做個能輸入模糊查詢提醒的功能元扔。自己也參考了很多的資料最后做個總結孕锄,實現如下:
方法一:
1迹冤、效果圖
2入挣、實現代碼
這里是應用了<el-autocomplete>這一組件完成這個功能
HTML部分
<el-autocomplete
v-model="listQuery.deptName" //數據綁定用于整個的搜索功能
:fetch-suggestions="querySearchGroup"
placeholder="請選擇"
clearable //由于輸入了內容后只會顯示匹配的那一個信息想修改的話記得加這個可清空輸入框內容的功能
class="filter-item"
style="width: 168px;margin-top:0px"
@select="selectGroup"
@focus="groupListMe"
/>
JS部分
定義用于存儲數據的兩個數組
data() {
return {
groupArr: [],
groupList: [],
}
},
設置一個深度監(jiān)聽listQuery.deptName
watch: {
'listQuery.deptName': {
deep: true,
handler: function(newVal, oldVal) {
this.groupArr = []// 這是定義好的用于存放下拉提醒框中數據的數組
var len = this.groupList.length// groupList
var arr = []
for (var i = 0; i < len; i++) { // 根據輸入框中的值進行模糊匹配
if (this.groupList[i].name.indexOf(this.listQuery.deptName) >= 0) {
arr.push({
value: this.groupList[i].name,
id: this.groupList[i].code
})
}
}
this.groupArr = arr
}
}
},
在方法中獲取
methods: {
groupListMe() {
getDictInfo().then(res => { // getDictInfo()這里是調用后臺接口
if (res.data) {
this.groupList = []
this.groupArr = []
this.groupList = res.data.list
for (const item of this.groupList) {
this.groupArr.push({
value: item.name, //這里一定是value: '值'
id: item.code
})
}
}
})
.catch(err => {
console.log(err)
})
},
querySearchGroup(queryString, cb) {
var groupArr = this.groupArr
cb(groupArr)
},
selectGroup(val) {
this.groupId = val.code
},
}
方法二:
效果圖為el-select添加filterable屬性即可啟用搜索功能嚣州。默認情況下鲫售,Select 會找出所有l(wèi)abel屬性包含輸入值的選項。
<el-select v-model="listQuery.deptCode" clearable filterable placeholder="請選擇" style="top: -6px;">
<el-option v-for="o in DeptOptions"
:key="o.code"
:label="o.name"
:value="o.name" />
</el-select>
DeptOptions的內容是從接口中獲取的该肴。getDictInfo為調用接口的方法情竹,關于詳細請見關于Get類型接口以及關于Post類型接口。
getOptionsData() {
getDictInfo().then(res => {
this.DeptOptions = res.data.list
console.log('treeList', this.DeptOptions)
})
},
3匀哄、總結
基本的實現就是如上步驟啦秦效!如有錯誤請多指教
關于官方文檔中el-autocomplete的用法
關于官方文檔中el-select的用法
其他關于接口的問題可以參考我的其他文章噢 ~
謝謝瀏覽!點個贊再走吧~