前端查询页面会有许多下拉框需要从后端拉取数据显示,考虑封装一个组件进行使用。
props中定义的是组件使用方可以传递的数据,组件封装比较简陋,从后端查询数据的代码可自行更改。
<template>
<div>
<el-select v-model="svalue" :placeholder="text" filterable>
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
</el-select>
</div>
</template>
<script>
import {
loadDictionaryIdAndValueList,
loadSubjectTypeIdAndNameList,
loadCategoryIdAndNameList
} from "../../api/index";
export default {
name: "tlSelect",
data() {
return {
options: [],
svalue: "",
text: "",
commonRequest: {
requestHead: {
version: "",
businessType: "",
deviceId: "",
deviceType: "",
encryption: ""
},
body: {}
},
fileType: {
label: "name",
value: "id"
}
};
},
methods: {
//转换下拉框下的字段
_dataTransform(data) {
let _data = [];
for (let i = 0; i < data.length; i++) {
_data[i] = {};
_data[i].label = data[i][this.fileType.label];
_data[i].value = data[i][this.fileType.value];
}
return _data;
}
},
watch: {
//判断下拉框的值是否有改变
svalue(val, oldVal) {
if (val != oldVal) {
this.$emit("input", this.svalue);
}
}
},
props: {
selectType: {
type: String
},
dictName: {
type: String
},
value: {
type: String
},
placeholder: {
type: String
}
},
mounted() {
//初始话下拉框的值
this.svalue = this.value;
this.text = this.placeholder;
let requestMethod = loadSubjectTypeIdAndNameList;
let param = "";
if (this.selectType === "SubjectCategory") {
requestMethod = loadCategoryIdAndNameList;
} else if (this.selectType === "SubjectType") {
requestMethod = loadSubjectTypeIdAndNameList;
} else if (this.selectType === "Dictionary") {
requestMethod = loadDictionaryIdAndValueList;
this.commonRequest.body = this.dictName;
param = this.commonRequest.body;
this.fileType = {
label: "value",
value: "id"
};
}
requestMethod(param)
.then(resp => {
if (resp.responseHead.code === "0") {
this.options = this._dataTransform(resp.body);
}
})
.catch(error => {
console.log(error);
});
}
};
</script>
本文介绍如何基于Element-UI封装一个简单的下拉框Vue组件,适用于前端查询页面从后端拉取数据展示。组件设计允许使用者通过props传递所需数据,并且后端查询逻辑可根据实际情况灵活调整。
3266

被折叠的 条评论
为什么被折叠?



