问题描述
使用elementUI中select远程搜索功能时,搜索一次后,点击下拉列表选项后,重新搜索时,输入无效,需要删除输入框内容,再次输入才会生效
解决思路
- 监听select的visible-change下拉框出现/隐藏时触发事件
- 下拉框收起时,清空查询query的值
- 下拉框展开时,判断query是否为空,并且查询出来的列表与初始列表是否相同;如果不同,则为输入框添加失焦事件blur
具体代码:
<template>
<div class="content">
<el-select
v-model="value"
class="selectClass"
multiple
collapse-tags
collapse-tags-tooltip
filterable
remote
reserve-keyword
placeholder="请输入关键词"
:remote-method="remoteMethod"
:loading="loading"
@visible-change="visibleChange"
@change="changeValue"
ref="select"
>
<el-option
v-for="item in options1"
:key="item.value"
:label="item.label"
:value="item.value"
>
</el-option>
</el-select>
</div>
</template>
<script>
export default {
data() {
return {
value: [],
loading: false,
options:[{
value: '选项1',
label: '黄金糕'
}, {
value: '选项2',
label: '双皮奶'
}, {
value: '选项3',
label: '蚵仔煎'
}, {
value: '选项4',
label: '龙须面'
}, {
value: '选项5',
label: '北京烤鸭'
}],
options1: [], // 查询出来的列表
query: "", // 查询变量
};
},
mounted() {},
watch: {
options() {
this.options1 = this.options;
},
},
methods: {
// 输入框搜索时触发
remoteMethod(query) {
this.query = query;
this.$nextTick(() => {
if (query !== "") {
this.loading = true;
setTimeout(() => {
this.loading = false;
this.options1 = this.options.filter((item) => {
return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
});
}, 200);
} else {
this.options1 = this.options;
}
});
},
// 下拉框出现/隐藏触发
visibleChange(value) {
if (value === false) {
this.query = "";
} else {
if (this.query === "" && this.options.length !== this.options1.length) {
this.$nextTick(() => {
this.remoteMethod("");
this.$refs.select.blur();
});
}
}
},
changeValue() {
this.$emit("change", this.value);
},
},
};
</script>