vue + element的动态下拉框封装
父组件
<template>
<div>
<apiSelect @item="apiSelectM" />
</div>
</template>
<script>
import apiSelect from "@/components/apiSelect";
export default {
data() {
return {};
},
mounted() {},
methods: {
apiSelectM(e) {
console.log(e);
},
},
components: {
apiSelect,
},
};
</script>
<style lang="scss" scoped>
</style>
子组件
<template>
<div>
<el-autocomplete
v-model="autocompleteVal"
:fetch-suggestions="querySearchAsync"
placeholder="请输入内容"
@blur="handleBlur"
@select="handleSelect"
@input="handleInput"
></el-autocomplete>
</div>
</template>
<script>
export default {
data() {
return {
selectName: "",
autocompleteVal: "",
canObj: {},
};
},
props: {
labelArr: {
type: Array,
default() {
return [];
},
},
nameLabel: {
type: String,
default: "",
},
labelArrKuo: {
// 展示数组括号里的
type: Array,
default() {
return [];
},
},
phoneLabel: {
type: String,
default: "",
},
urlLabel: {
type: String,
default: "",
},
can: {
type: Object,
default() {
return {};
},
},
zhi: {
type: String,
default: "",
},
},
mounted() {
this.$nextTick(() => {
this.autocompleteVal = this.zhi;
this.selectName = this.zhi;
});
},
methods: {
nameZs(item) {
var str = item[this.nameLabel];
var kuo = "";
if (this.labelArrKuo.length * 1) {
kuo = "( ";
for (let j = 0; j < this.labelArrKuo.length; j++) {
if (item[this.labelArrKuo[j]]) {
kuo += item[this.labelArrKuo[j]] + " ";
}
}
kuo += " )";
}
str += kuo == "( )" ? "" : kuo;
if (this.phoneLabel) {
str += " - " + item[this.phoneLabel];
}
return str;
},
handleBlur(e) {
this.autocompleteVal = this.selectName;
},
handleSelect(item) {
this.selectName = item[this.nameLabel];
this.autocompleteVal = item[this.nameLabel];
this.$emit("item", item);
},
handleInput(e) {
if (!e) {
this.selectName = "";
this.$emit("item", {});
}
},
querySearchAsync(queryString, cb) {
if (!queryString || queryString == "1") {
cb([]);
return;
}
var data = {
keyword: queryString,
size: 99999,
page: 1,
};
for (let i in this.can) {
data[i] = this.can[i];
}
var restaurants = [];
this.$url.MUrl(this.urlLabel, data).then((e) => {
if (e.status == 200) {
e.data.list.forEach((item) => {
item.value = item[this.nameLabel];
});
var dataList = e.data.list;
for (let i = 0; i < dataList.length; i++) {
var item = dataList[i];
item.value = this.nameZs(item);
for (let j = 0; j < this.labelArr.length; j++) {
if (item[this.labelArr[j]]) {
item.nameShow += item[this.labelArr[j]];
}
}
}
restaurants = e.data.list;
var results = queryString
? restaurants.filter(this.createStateFilter(queryString))
: restaurants;
if (results.length == 0) {
results = [{ value: "暂无数据" }];
}
cb(results);
}
});
},
// 过滤出state.value中包含queryString的记录
createStateFilter(queryString) {
return (state) => {
return (
state.nameShow.toLowerCase().indexOf(queryString.toLowerCase()) != -1
);
};
},
},
};
</script>
<style lang="scss" scoped>
</style>
使用效果
浙公网安备 33010602011771号