有个功能需要关联话题,话题需要能在线搜索,想到了 el-select 的远程搜索功能,由于官方案例没有远程调用方法,一直都无法理解如何使用。也被部分其他资料误导,终于尝试成功。特意做个笔记。
html 代码 《el-select v-model="form.topic_id" filterable remote reserve-keyword placeholder="搜索话题" :remote-method="searchTopicMethod" :loading="searchTopicLoading"》 《el-option v-for="item in form.topic_options" :key="item.value" :label="item.label" :value="item.value"》 《/el-option》 《/el-select》
JS 代码
data:{
searchTopicLoading:false, //搜索话题锁
topicList:[],
form:{
topic_id: '', //选中话题ID
topic_options:[], //可选话题列表数据
},
},
method:{
//搜索话题回调函数
searchTopicMethod(query){
if (query !== '') {
this.searchTopicLoading = true; //锁住
let self = this;
$.ajax({
data: {act:'searchTopic', 'keyword': query}
,url : 'http://api.xx.com/searchTopic'
, success: function (res) {
if (res.code == 200) {
//拿到数据后,渲染到 this.topicList
//不可直接赋值到 this.form.topic_options,亲自试过N次
self.topicList = res.data.options;
} else {
self.$message({
message: res.msg,
type: 'error',
duration: 2000, //显示时间后自动关闭
showClose: true,
});
}
}
});
/**
* 搜索内容渲染到下拉框
* 从 this.topicList 把数据赋值到 this.form.topic_options
* 只有这样才能起作用
*/
setTimeout(() => {
this.searchTopicLoading = false;
this.form.topic_options = this.topicList.filter(item => {
return item.label.toLowerCase()
.indexOf(query.toLowerCase()) > -1;
});
}, 200);
} else {
this.form.topic_options = [];
}
},
}总结:
1、AJAX获得数据必须按照 el-option for 格式来准备 JSON。
2、AJAX获得的数据先放入 this.topicList,然后加载到 this.form.topic_options 。否则会无效,this 里面的变量会自带 filter 方法 。(非专业理解)