效果与直接使用el-select一样,多处用el-select显得代码冗余就进行了封装
效果图:
el-select封装:
<template><div class="my-select"><el-selectv-model="person.modelValue":placeholder="placeholder"@change="changeSelect"><el-optionv-for="item in options":key="item[val]":label="item[name]":value="item[val]"></el-option></el-select></div>
</template><script setup>
import { reactive, watch } from "vue";
const emits = defineEmits(["onChange"]);
let props = defineProps({val: {type: String,default: "value",},name: {type: String,default: "label",},placeholder: {type: String,default: "请选择",},options: {type: Array,default: [],},value: {type: [Number, String],default: "",},
});
console.log(props);
const person = reactive({modelValue: "",
});
function changeSelect(val) {emits("onChange", val);
}
watch(() => props.value,(val) => {// 用于回显person.modelValue = val;},{ deep: true, immediate: true }
);</script>
<style scoped lang='less'>
</style>
功能组件内使用el-select封装组件:
<template><div><el-form ref="form" label-width="120px" label-position="left"><el-form-item label="选择第几个选项"><MySelectwidth="220px"title="确定"@onChange="addDeciceType":options="person.optionsList":val="'val'":name="'name'"placeholder="请选择":value="1"></MySelect></el-form-item></el-form></div>
</template><script setup>
import { reactive, onMounted } from "vue";
import MySelect from "../components/MySelect.vue";
const person = reactive({optionsList: [{ name: "第1个选项", val: 1 },{ name: "第2个选项", val: 2 },{ name: "第3个选项", val: 3 },],
});
function addDeciceType(val) {console.log(val);
}
onMounted(() => {});
</script>
<style scoped lang='less'>
</style>