因为原生的select不太好封装,所以就选用了div+ul来模拟下拉框选择,本文使用的是vue3将其封装成一个组件,需要用到vueuse,不过如果不认识这个插件或者不想安的,也不碍事,这个插件就是让我们封装的组件的在组件范围之外点击可以关闭显示下拉框
1. 封装
<script lang="ts" setup>
import {getCurrentInstance, ref} from "vue";
import {onClickOutside} from "@vueuse/core";
interface Props {
width?: number, // 宽度
height?: number, // 高度
options: any, // option数组,下拉框显示内容,为数组类型,如:['选项1','选项2',...]
selectValue?: any, // 默认展示的option
}
const props = withDefaults(defineProps<Props>(), {
width: 150,
height: 30,
});
const {proxy} = getCurrentInstance();
// 组装样式
const selectStyle = {
width: props.width + "px",
height: props.height + "px",
};
// 控制显示下拉框
const show = ref(false);
// 获取本组件实例
const target = ref();
// 选中的值,其中的判断是看父组件是否传递有默认展示的值&#x