一个最简单的下拉菜单demo,没有华丽的外观,需要自己调
-
Dropdown.vue
-
<template> <div class="dropdown"> <button class="dropdown-toggle" @click="toggleDropdown"> {{ selectedOption }} </button> <ul v-show="isDropdownOpen" class="dropdown-menu"> <li v-for="option in options" :key="option.id" @click="selectOption(option)"> {{ option.label }} </li> </ul> </div> </template> <script> export default { name: 'MyDropdown', props: { options: { type: Array, default: () => [ { id: 1, label: '选项1' }, { id: 2, label: '选项2' }, { id: 3, label: '选项3' }, ], }, }, data() { return { isDropdownOpen: false, selectedOption: "请选择" } }, methods: { toggleDropdown() { this.isDropdownOpen = !this.isDropdownOpen; }, selectOption(option) { this.selectedOption= option.label; this.isDropdownOpen = false; this.$emit('select', option); } }, }; </script> <style> .dropdown { position: relative; } .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; padding: 0.5rem 1rem; background-color: #fff; border: 1px solid #ccc; cursor: pointer; } .dropdown-menu { padding: 0; margin: 0; list-style: none; background-color: #fff; border: 1px solid #ccc; } .dropdown-menu li { padding: 0.5rem 1rem; cursor: pointer; } .dropdown-menu li:hover { background-color: #f5f5f5; } </style>
-
Page2.vue
<template> <div id="page2" class="page close"> <div> <!-- 想要对调成功,@select 很重要,不要用括号接收值 --> <MyDropdown :options="options" @select="handleSelectOption" /> </div> </div> </template> <script> // 导出下拉组件 import MyDropdown from './Dropdown.vue' export default { name: 'MyPage2', components: { MyDropdown }, // 注册下拉组件 data() { return { options: [ // 定义数据 { id: 1, label: '选项1' }, { id: 2, label: '选项2' }, { id: 3, label: '选项3' }, ], selected: '选项1' } }, methods: { handleSelectOption(e) { // 需要回调的函数 console.log(e); }, }, } </script> <style> #page2 { /* border: 1px solid #c7c7c7; */ background-color: #0000; padding: 2px; } </style>
重点
下拉菜单里面的 this.$emit('select', option);
很重要,调用组件定义一个@select,这个就是指定回去的,
后面是需要传递的参数