1. 在template加入如下標簽
<el-form-item label="文章庫" :label-width="formLabelWidth" > <el-autocomplete v-model="addTopic.name" :fetch-suggestions="querySearchAsync" placeholder="請輸入文章標題" @select="handleSelect" :clearable="true" ></el-autocomplete> </el-form-item>
2. 在template加入如下標簽
//queryString 為在框中輸入的值 //callback 回調函數,將處理好的數據推回 async querySearchAsync (queryString, cb) { if (queryString !== '') { let res = await requestSearchTopic(queryString) let {data, status} = res.data if (status === 200) { for (let i of data) { //在這里為這個數組中每一個對象加一個value字段, 因為autocomplete只識別value字段並在下拉列中顯示 i.value = i.name + '\xa0\xa0\xa0\xa0作者:' + i.creator } let restaurants = data clearTimeout(this.timeout) // 設置定時任務將restaurants返回 this.timeout = setTimeout(() => { cb(restaurants) }, 50 * Math.random()) } } },
@select="handleSelect" 是選中某一列觸發的事件,在這里item為選中字段所在的對象
handleSelect (item) { this.addTopic.topicId = item.id this.addTopic.name = item.name this.addTopic.creator = item.creator },
需要注意的地方:
后台獲取的數組中每一個對象必須要有一個value字段, 因為autocomplete只識別value字段並在下拉列中顯示
參考文檔:https://blog.csdn.net/qq_37746973/article/details/78402812
