uni-app 需要一个自定义下拉框的组件
uni-app 需要一个自定义下拉框的组件
下拉框里的内容我可以自己放组件进去 正常的下拉框是无法自己放组件进去展示出来
2 回复
在uni-app中创建一个自定义下拉框组件,可以通过组合使用<view>
、<scroll-view>
和<picker>
等组件来实现。以下是一个简单的自定义下拉框组件的示例代码,包括组件的创建和使用。
自定义下拉框组件 (MyDropdown.vue)
<template>
<view class="dropdown">
<view class="selected-text" @tap="toggleDropdown">{{selectedText}}</view>
<view class="dropdown-menu" v-if="isVisible">
<scroll-view scroll-y="true" style="height: 150px;">
<view v-for="(item, index) in options" :key="index" class="dropdown-item" @tap="selectItem(index)">
{{item}}
</view>
</scroll-view>
</view>
</view>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true
},
initialValue: {
type: String,
default: ''
}
},
data() {
return {
selectedText: this.initialValue,
isVisible: false
};
},
methods: {
toggleDropdown() {
this.isVisible = !this.isVisible;
},
selectItem(index) {
this.selectedText = this.options[index];
this.isVisible = false;
this.$emit('change', this.selectedText);
}
},
mounted() {
if (!this.selectedText && this.options.length > 0) {
this.selectedText = this.options[0];
}
}
};
</script>
<style scoped>
.dropdown {
position: relative;
width: 100%;
}
.selected-text {
padding: 10px;
border: 1px solid #ccc;
background-color: #fff;
cursor: pointer;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
right: 0;
border: 1px solid #ccc;
background-color: #fff;
z-index: 1000;
}
.dropdown-item {
padding: 10px;
cursor: pointer;
}
.dropdown-item:hover {
background-color: #f0f0f0;
}
</style>
使用自定义下拉框组件 (App.vue)
<template>
<view>
<MyDropdown :options="options" @change="handleChange" />
</view>
</template>
<script>
import MyDropdown from './components/MyDropdown.vue';
export default {
components: {
MyDropdown
},
data() {
return {
options: ['Option 1', 'Option 2', 'Option 3']
};
},
methods: {
handleChange(value) {
console.log('Selected:', value);
}
}
};
</script>
以上代码展示了如何创建一个简单的自定义下拉框组件,并在父组件中使用它。MyDropdown
组件接收一个options
数组作为下拉选项,并通过change
事件将选中的值传递给父组件。样式部分可以根据实际需求进行调整。