接手别人的项目,明明已经封装好了下拉框的组件,奈何某些人嫌弃不好用不能试用其他所有的接口。没办法,自己封一个组件吧。各位觉得好用可以收藏一下,我也是为了下次懒得动手就拿上来保存着吧。
<template>
<div>
<a-select
v-model="value_"
:default-value="defaultValue"
@change="handleChange"
:placeholder="placeholder"
allowClear
>
<a-select-option v-for="item in selectList" :key="item[props.id]" :value="item[props.id]">
{{ item[props.label] }}
</a-select-option>
</a-select>
</div>
</template>
<script>
import { getPublicSelectList } from "@/api/api.js";
export default {
name: 'PublicSelect',
props: {
/*下拉框的接口地址url */
url: {
type: String,
default: ''
},
/* 如果当前下卡框有参数,传params */
params: {
type: Object,
default: () => { }
},
/* props对应下拉框的id和label,默认情况下id为‘value’,label为‘label’ */
props: {
type: Object,
default: {
id: 'value',
label: 'label'
}
},
/* 提示文字 */
placeholder: {
type: String,
default: '请选择'
},
/* 如果需要默认值,对应的是下拉框id */
defaultValue: {
type: String,
default: ''
},
/* 绑定的字段 */
value: {
type: String,
default: ''
},
},
data() {
return {
selectList: [],
value_:this.value?this.value:undefined
}
},
watch: {
props: {
deep: true,
handler(newvalue, oldvalue) {
if (Object.values(newvalue).length) {
const first = Object.keys(newvalue)
const second = Object.keys(oldvalue)
if (first.length != second.length) {
return
}
for (let i in newvalue) {
if (newvalue[i] != oldvalue[i]) {
return
}
}
this.init()
}
}
},
value:{
handler(newvalue, oldvalue) {
if(!newvalue){
this.value_ = undefined
}
}
}
},
created() {
this.init()
},
methods: {
init() {
getPublicSelectList(this.url, this.params).then(res => {
this.selectList = res.result
})
},
handleChange(value) {
this.$emit('update:value', value)
},
},
}
</script>
<style lang='less' scoped>
</style>
然后使用的地方
<PublicSelect
:value.sync="queryParam.status"
url="/api/list/payment_status"
:props="{id:'value',label:'label'}"
placeholder="交易状态"
style="width: 180px"/>