需求:项目中一般存在很多下拉框,比如搜索的下拉框,表单增加的下拉框,他们数据需要从后台去获取,每次一个一个写slelect,option其实造成了大量代码重复,这个时候可以封装成一个公共的组件供所有下拉框功能使用;
开发:
1:数据来源和后台协商保持同一个接口,不同参数获取不同数据
2:父子组件通信使用props,子组件接收参数类型和绑定的value
3:使用枚举的方式,将需要的类型存起来方便维护使用
4:使用$emit和父组件通信,获取选中的数据
完整代码:创建文件dict.vue
<template>
<el-select v-model="dictValue" placeholder="请选择" filterable clearable @change="handleButton">
<el-option
v-for="item in searchBarList"
:key="item.code"
:label="item.name"
:value="item.code"
/>
</el-select>
</template>
<script>
import { getApi } from '@/api/user';
export default {
name: 'Dict',
props: ['dictType', 'value'],
data() {
return {
searchBarList: [],
dictValue: this.value,
dictEnumeration: {
0: 6, // 模块
1: 13// 方向
}
};
},
watch: {
// 判断下拉框的值是否有改变
value(val) {
this.dictValue = val;
},
dictValue(val, oldVal) {
if (val !== oldVal) {
this.$emit('input', val);
}
}
},
mounted() {
this.getDict(this.dictEnumeration[this.dictType]);
},
methods: {
async getDict(id) {
const json= {
dictid: id
}
const resp = await getApi(json);
this.searchBarList = data;
},
// 下拉框点击事件
handleButton() {
this.$emit('changeType', this.dictValue);
}
}
};
</script>
使用方式:
1:引入组件,注册组件
import Dict from '@/components/dict';
components: {
Dict
},
2:使用组件
<dict v-model="formline.partid" :dict-type="'0'" @changeType="changePart" />
3:获取选中的值
changePart(value) {
console.log(value);
}
结束~~