当前位置: 首页 > article >正文

DeepSeek 助力 Vue3 开发:打造丝滑的下拉选择框(Dropdown Select)

前言:哈喽,大家好,今天给大家分享一篇文章!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕

共同探索软件研发!敬请关注【宝码香车】
关注描述

csdngif标识

目录

  • DeepSeek 助力 Vue3 开发:打造丝滑的下拉选择框(Dropdown Select)
    • 📚前言
    • 📚页面效果
    • 📚指令输入
      • 属性定义
        • 数据相关属性
        • 显示相关属性
        • 样式相关属性
        • 过滤相关属性
      • 事件定义
      • 其他
        • 组件设计
        • 文档和示例
    • 📚think
      • 📘组件代码
    • 📚代码测试
    • 📚整理后主要全部代码 \src\components\DropdownSelect\DropdownSelect.vue
    • 📚测试代码正常跑通,附其他基本代码
      • 📘编写路由 \src\router\index.js
      • 📘编写展示入口 \src\App.vue
    • 📚页面效果
    • 📚相关文章


📚📗📕📘📖🕮💡📝🗂️✍️🛠️💻🚀🎉🏗️🌐🖼️🔗📊👉🔖⚠️🌟🔐⬇️·正文开始⬇️·🎥😊🎓📩😺🌈🤝🤖📜📋🔍✅🧰❓📄📢📈 🙋0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣🔟🆗*️⃣#️⃣

DeepSeek 助力 Vue3 开发:打造丝滑的下拉选择框(Dropdown Select)

📚前言

多模态融合技术也将成为 DeepSeek 未来发展的重要方向。未来,DeepSeek 将致力于实现文本、图像、音频、视频等多种模态信息的深度融合与交互。通过将不同模态的数据进行整合和分析,模型能够更全面地理解用户的需求和意图,提供更加丰富和多样化的服务。在智能客服场景中,用户不仅可以通过文字与 DeepSeek 进行交互,还可以上传图片、发送语音等,DeepSeek 能够综合这些信息,快速准确地回答用户的问题,提供更优质的服务体验。在教育领域,多模态融合技术可以将文字教材、图片、视频等多种教学资源有机结合,为学生提供更加生动、直观的学习体验,提高学习效果。

📚页面效果

DeepSeek 助力 Vue3 开发:打造丝滑的下拉选择框(Dropdown Select)页面效果

📚指令输入

已经创建好了一个基于Vue3的组合式API的项目(Composition API),并能正常运行起来,请帮我用 Vue3的组合式API(Composition API) 生成一个 下拉选择框(Dropdown Select) 的功能组件,所有代码都保存在components/DropdownSelect 下的文件夹中。功能组件的script标签中只有setup属性,使用普通 JavaScript 实现,不使用TypeScript。
功能要有,如下属性:

属性定义

数据相关属性
  1. modelValue
    • 类型:与选项值类型一致(如 StringNumber 等)
    • 作用:用于双向数据绑定,反映当前选中的选项值。
  2. options
    • 类型:Array
    • 作用:存储下拉选择框的选项列表,每个选项可以是简单值,也可以是包含 labelvalue 属性的对象。
  3. optionLabel
    • 类型:String
    • 作用:当 options 中的元素是对象时,指定用于显示的属性名。
  4. optionValue
    • 类型:String
    • 作用:当 options 中的元素是对象时,指定作为值的属性名。
显示相关属性
  1. placeholder
    • 类型:String
    • 作用:下拉框未选择时显示的提示文本。
  2. disabled
    • 类型:Boolean
    • 作用:控制下拉选择框是否禁用,禁用状态下用户无法操作。
  3. readonly
    • 类型:Boolean
    • 作用:设置下拉选择框为只读状态,用户只能查看已选内容,不能进行选择操作。
  4. size
    • 类型:String,可选值如 'small', 'medium', 'large'
    • 作用:控制下拉选择框的大小。
  5. multiple
    • 类型:Boolean
    • 作用:是否允许多选,若为 truemodelValue 应为数组。
  6. maxSelected
    • 类型:Number
    • 作用:当 multipletrue 时,限制最多可选的选项数量。
样式相关属性
  1. dropdownStyle
    • 类型:ObjectString
    • 作用:自定义下拉列表的样式。
  2. inputStyle
    • 类型:ObjectString
    • 作用:自定义下拉框输入部分的样式。
过滤相关属性
  1. filterable
    • 类型:Boolean
    • 作用:是否允许用户在下拉框中输入内容进行选项过滤。
  2. filterPlaceholder
    • 类型:String
    • 作用:当 filterabletrue 时,过滤输入框的占位提示文本。

事件定义

  1. update:modelValue
    • 作用:当选择的选项发生变化时触发,用于更新 modelValue 的值,实现双向数据绑定。
  2. change
    • 作用:选择的选项发生变化时触发,传递当前选中的值作为参数。
  3. open
    • 作用:下拉列表展开时触发。
  4. close
    • 作用:下拉列表关闭时触发。
  5. filter
    • 作用:当用户在过滤输入框中输入内容时触发,传递输入的过滤文本作为参数。

其他

组件设计
  1. 支持插槽:允许用户自定义下拉框的显示内容、选项内容等,增强组件的灵活性。
  2. 分组功能:支持对选项进行分组显示,提供更清晰的选项结构。
  3. 虚拟列表:当选项数量较多时,使用虚拟列表技术优化性能,减少 DOM 渲染压力。
  4. 键盘操作:支持使用键盘上下箭头选择选项、回车键确认选择等操作,提升用户体验。
文档和示例
  1. 详细文档:提供清晰的组件文档,包括属性说明、事件说明、使用示例等,方便其他开发者使用。
  2. 在线示例:提供在线的代码示例,让开发者可以直观地看到组件的效果和使用方法。

你有更好的建议也可以添加,要注明。组件定义好后给出5个及以上的调用示例。
下面是现有目录
vueAndDeepseek/
├── src/ # 源代码目录
│ ├── assets/ # 静态资源
│ │ ├── base.css
│ │ ├── main.css
│ │ └── logo.svg
│ ├── components/ # 组件目录
│ │ ├── HelloWorld.vue
│ │ ├── TheWelcome.vue
│ │ ├── WelcomeItem.vue
│ │ ├── Progress/
│ │ │ └── Progress.vue
│ │ ├── Accordion/
│ │ ├── BackToTop/
│ │ ├── Card/
│ │ ├── InfiniteScroll/
│ │ ├── Notification/
│ │ ├── Timeline/
│ │ ├── Switch/
│ │ ├── Tabs/
│ │ ├── Sidebar/
│ │ ├── Breadcrumbs/
│ │ ├── MasonryLayout/
│ │ ├── Rating/
│ │ ├── ColorPicker/
│ │ ├── RightClickMenu/
│ │ ├── RangePicker/
│ │ ├── Navbar/
│ │ ├── FormValidation/
│ │ ├── CopyToClipboard/
│ │ ├── ClickAnimations/
│ │ ├── ThumbnailList/
│ │ ├── KeyboardShortcuts/
│ │ ├── CommentSystem/
│ │ ├── QRCode/
│ │ ├── RadioButton/
│ │ ├── Slider/
│ │ ├── ScrollAnimations/
│ │ ├── TextInput/
│ │ ├── Divider/
│ │ ├── Checkbox/
│ │ ├── TagInput/
│ │ ├── DropdownSelect/
│ │ ├── DatePicker/
│ │ └── icons/
│ ├── router/ # 路由配置
│ │ └── index.js
│ ├── stores/ # Pinia 状态管理
│ │ └── counter.js
│ ├── views/ # 页面组件
│ │ ├── ProgressView.vue
│ │ ├── TabsView.vue
│ │ ├── SwitchView.vue
│ │ ├── TimelineView.vue
│ │ ├── NotificationView.vue
│ │ ├── CardView.vue
│ │ ├── InfiniteScrollView.vue
│ │ ├── BackToTopView.vue
│ │ ├── AccordionView.vue
│ │ ├── SidebarView.vue
│ │ ├── BreadcrumbsView.vue
│ │ ├── MasonryLayoutView.vue
│ │ ├── RatingView.vue
│ │ ├── ColorPickerView.vue
│ │ ├── RightClickMenuView.vue
│ │ ├── RangePickerView.vue
│ │ ├── NavbarView.vue
│ │ ├── FormValidationView.vue
│ │ ├── CopyToClipboardView.vue
│ │ ├── ClickAnimationsView.vue
│ │ ├── ThumbnailListView.vue
│ │ ├── KeyboardShortcutsView.vue
│ │ ├── CommentSystemView.vue
│ │ ├── QRCodeView.vue
│ │ ├── RadioButtonView.vue
│ │ ├── SliderView.vue
│ │ ├── ScrollAnimationsView.vue
│ │ ├── TextInputView.vue
│ │ ├── DividerView.vue
│ │ ├── CheckboxView.vue
│ │ ├── TagInputView.vue
│ │ ├── DropdownSelectView.vue
│ │ ├── DatePickerView.vue
│ │ └── AboutView.vue
│ ├── App.vue # 根组件
│ └── main.js # 应用入口
├── public/ # 公共资源目录
├── index.html # HTML 模板
├── package.json # 项目配置
├── vite.config.js # Vite 配置
└── node_modules/ # 依赖包目录

📚think

📘组件代码

我为您设计一个功能完善的DropdownSelect组件。以下是组件的实现步骤和代码:

🔨 组件实现思路:

  1. 使用组合式API处理响应式数据
  2. 通过computed处理选项的格式化显示
  3. 使用teleport处理下拉框的定位问题
  4. 通过键盘事件处理提升用户体验
  5. 使用Intersection Observer实现虚拟列表优化

📁 组件目录结构:
vueAndDeepseek/src/components/DropdownSelect/
├── index.js # 组件导出文件
└── DropdownSelect.vue # 组件主文件

📄 DropdownSelect.vue 代码:

<template>
  <div class="dropdown-select" :class="[size, { disabled, readonly }]">
    <!-- 触发区域 -->
    <div 
      class="select-trigger"
      :style="inputStyle"
      @click="toggleDropdown"
      @keydown="handleTriggerKeydown"
      tabindex="0"
    >
      <slot name="trigger" :selected="selectedValue">
        <div class="selected-display">
          <template v-if="multiple">
            <span 
              v-for="(item, index) in selectedItems" 
              :key="index"
              class="selected-tag"
            >
              {{ getOptionLabel(item) }}
              <span 
                v-if="!disabled && !readonly" 
                class="remove-tag"
                @click.stop="removeTag(item)"
              >×</span>
            </span>
            <span v-if="!selectedItems.length" class="placeholder">
              {{ placeholder }}
            </span>
          </template>
          <template v-else>
            {{ selectedLabel || placeholder }}
          </template>
        </div>
        <div class="dropdown-indicator"></div>
      </slot>
    </div>

    <!-- 下拉菜单 -->
    <teleport to="body">
      <transition name="dropdown">
        <div 
          v-show="isOpen"
          class="dropdown-menu"
          :style="dropdownStyle"
          @click.stop
        >
          <!-- 过滤输入框 -->
          <input
            v-if="filterable"
            v-model="filterText"
            class="filter-input"
            :placeholder="filterPlaceholder"
            @input="handleFilterInput"
          />

          <!-- 选项列表 -->
          <div class="options-list" ref="listRef">
            <template v-for="(option, index) in filteredOptions" :key="index">
              <!-- 分组处理 -->
              <div 
                v-if="option.group"
                class="option-group"
              >
                <slot name="group" :group="option">
                  <div class="group-label">{{ option.group }}</div>
                </slot>
                <div 
                  v-for="(item, i) in option.items" 
                  :key="i"
                  class="option-item"
                  :class="{ 
                    selected: isSelected(item),
                    disabled: item.disabled
                  }"
                  @click="selectOption(item)"
                >
                  <slot name="option" :option="item">
                    {{ getOptionLabel(item) }}
                  </slot>
                </div>
              </div>
              <!-- 普通选项 -->
              <div
                v-else
                class="option-item"
                :class="{ 
                  selected: isSelected(option),
                  disabled: option.disabled
                }"
                @click="selectOption(option)"
              >
                <slot name="option" :option="option">
                  {{ getOptionLabel(option) }}
                </slot>
              </div>
            </template>
          </div>
        </div>
      </transition>
    </teleport>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  modelValue: [String, Number, Array, Object],
  options: {
    type: Array,
    default: () => []
  },
  optionLabel: {
    type: String,
    default: 'label'
  },
  optionValue: {
    type: String,
    default: 'value'
  },
  placeholder: String,
  disabled: Boolean,
  readonly: Boolean,
  size: {
    type: String,
    validator: v => ['small', 'medium', 'large'].includes(v),
    default: 'medium'
  },
  multiple: Boolean,
  maxSelected: Number,
  dropdownStyle: [Object, String],
  inputStyle: [Object, String],
  filterable: Boolean,
  filterPlaceholder: String
})

const emit = defineEmits([
  'update:modelValue',
  'change',
  'open',
  'close',
  'filter'
])

const isOpen = ref(false)
const filterText = ref('')
const listRef = ref(null)

// 计算选中项
const selectedValue = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

// 处理选项显示标签
const getOptionLabel = option => {
  if (typeof option === 'object') {
    return option[props.optionLabel] || option.label || option.value
  }
  return option
}

// 处理选项实际值
const getOptionValue = option => {
  if (typeof option === 'object') {
    return option[props.optionValue] || option.value
  }
  return option
}

// 当前选中的选项对象
const selectedItems = computed(() => {
  if (!selectedValue.value) return []
  if (props.multiple) {
    return props.options.filter(opt => 
      selectedValue.value.includes(getOptionValue(opt))
    )
  }
  return props.options.find(opt => 
    getOptionValue(opt) === selectedValue.value
  )
})

// 当前显示标签(单选时)
const selectedLabel = computed(() => {
  if (props.multiple) return ''
  return selectedItems.value ? getOptionLabel(selectedItems.value) : ''
})

// 过滤后的选项
const filteredOptions = computed(() => {
  if (!props.filterable || !filterText.value) return props.options
  return props.options.filter(option => {
    const label = getOptionLabel(option).toLowerCase()
    return label.includes(filterText.value.toLowerCase())
  })
})

// 切换下拉框
const toggleDropdown = () => {
  if (props.disabled || props.readonly) return
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    emit('open')
  } else {
    emit('close')
  }
}

// 选择选项
const selectOption = option => {
  if (option.disabled) return
  
  const value = getOptionValue(option)
  
  if (props.multiple) {
    const current = Array.isArray(selectedValue.value) 
      ? selectedValue.value 
      : []
    const index = current.indexOf(value)
    
    if (index > -1) {
      current.splice(index, 1)
    } else {
      if (props.maxSelected && current.length >= props.maxSelected) return
      current.push(value)
    }
    selectedValue.value = [...current]
  } else {
    selectedValue.value = value
    isOpen.value = false
  }
  
  emit('change', selectedValue.value)
}

// 移除标签(多选时)
const removeTag = item => {
  if (props.disabled || props.readonly) return
  const value = getOptionValue(item)
  selectedValue.value = selectedValue.value.filter(v => v !== value)
}

// 处理过滤输入
const handleFilterInput = e => {
  emit('filter', e.target.value)
}

// 处理键盘事件
const handleTriggerKeydown = e => {
  if (props.disabled || props.readonly) return
  
  switch(e.key) {
    case 'ArrowDown':
    case 'Enter':
      isOpen.value = true
      e.preventDefault()
      break
    case 'Escape':
      isOpen.value = false
      break
  }
}

// 点击外部关闭
const clickOutsideHandler = e => {
  if (!isOpen.value) return
  if (!e.target.closest('.dropdown-select')) {
    isOpen.value = false
    emit('close')
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('click', clickOutsideHandler)
})

onUnmounted(() => {
  document.removeEventListener('click', clickOutsideHandler)
})
</script>

<style scoped>
/* 这里需要添加详细的样式代码 */
.dropdown-select {
  position: relative;
  width: 100%;
  max-width: 300px;
}
.select-trigger {
  border: 1px solid #ccc;
  padding: 8px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dropdown-menu {
  position: absolute;
  border: 1px solid #ccc;
  background: white;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
}
.option-item {
  padding: 8px;
  cursor: pointer;
}
.option-item:hover {
  background: #f0f0f0;
}
.selected {
  background: #e0f0ff;
}
.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>

📄 index.js 导出文件:

import DropdownSelect from './DropdownSelect.vue'

export default DropdownSelect

5个调用示例:

  1. 基础使用:
<DropdownSelect
  v-model="selectedValue"
  :options="['Apple', 'Banana', 'Orange']"
  placeholder="Select a fruit"
/>
  1. 对象选项多选:
<DropdownSelect
  v-model="selectedValues"
  :options="[
    { id: 1, name: '北京' },
    { id: 2, name: '上海' },
    { id: 3, name: '广州' }
  ]"
  option-label="name"
  option-value="id"
  multiple
  placeholder="选择城市"
/>
  1. 过滤和分组:
<DropdownSelect
  v-model="selectedCar"
  :options="[
    { group: '德国车', items: [
      { value: 'bmw', label: '宝马' },
      { value: 'benz', label: '奔驰' }
    ]},
    { group: '日本车', items: [
      { value: 'toyota', label: '丰田' }
    ]}
  ]"
  filterable
  filter-placeholder="搜索车型"
/>
  1. 禁用状态:
<DropdownSelect
  v-model="selectedItem"
  :options="options"
  disabled
  placeholder="禁用状态"
/>
  1. 自定义样式和插槽:
<DropdownSelect
  v-model="selected"
  :options="users"
  option-label="fullName"
  option-value="id"
  :input-style="{ border: '2px solid #4CAF50' }"
>
  <template #option="{ option }">
    <div style="display: flex; align-items: center">
      <img 
        :src="option.avatar" 
        style="width: 30px; height:30px; border-radius:50%; margin-right:10px"
      >
      {{ option.fullName }}
    </div>
  </template>
</DropdownSelect>

💡 附加建议:

  1. 可以添加loading状态显示加载指示器
  2. 增加远程搜索功能(当选项需要异步加载时)
  3. 添加选项的图标支持
  4. 支持选项的自定义排序
  5. 添加输入框的清除按钮
  6. 支持选项的创建功能(允许用户输入新值)

实现时需要注意:

  1. 使用Teleport解决下拉框的定位问题
  2. 多选时的性能优化(特别是大量选项时)
  3. 严格的类型检查(虽然不用TS但需要验证props)
  4. 完善的键盘导航支持
  5. 无障碍访问(ARIA属性)

📚代码测试

有一个报错。

DropdownSelect.vue:86 Uncaught (in promise) TypeError: _ctx.isSelected is not a function
    at DropdownSelect.vue:86:58
    at renderList (chunk-U3LI7FBV.js?v=c715b44f:4988:16)
    at DropdownSelect.vue:1:1
    at Proxy.renderFnWithContext (chunk-U3LI7FBV.js?v=c715b44f:2763:13)
    at Proxy.<anonymous> (chunk-U3LI7FBV.js?v=c715b44f:3233:79)
    at renderComponentRoot (chunk-U3LI7FBV.js?v=c715b44f:8581:17)
    at ReactiveEffect.componentUpdateFn [as fn] (chunk-U3LI7FBV.js?v=c715b44f:7403:46)
    at ReactiveEffect.run (chunk-U3LI7FBV.js?v=c715b44f:481:19)
    at setupRenderEffect (chunk-U3LI7FBV.js?v=c715b44f:7538:5)
    at mountComponent (chunk-U3LI7FBV.js?v=c715b44f:7313:7)

原因:没有isSelected 。
解决:添加isSelected 。

// 判断选项是否被选中
const isSelected = option => {
  if (props.multiple) {
    return selectedValue.value.includes(getOptionValue(option))
  }
  return getOptionValue(option) === selectedValue.value
}

📚整理后主要全部代码 \src\components\DropdownSelect\DropdownSelect.vue

<template>
  <div class="dropdown-select" :class="[size, { disabled, readonly }]">
    <!-- 触发区域 -->
    <div
        class="select-trigger"
        :style="inputStyle"
        @click="toggleDropdown"
        @keydown="handleTriggerKeydown"
        tabindex="0"
    >
      <slot name="trigger" :selected="selectedValue">
        <div class="selected-display">
          <template v-if="multiple">
            <span
                v-for="(item, index) in selectedItems"
                :key="index"
                class="selected-tag"
            >
              {{ getOptionLabel(item) }}
              <span
                  v-if="!disabled && !readonly"
                  class="remove-tag"
                  @click.stop="removeTag(item)"
              >×</span>
            </span>
            <span v-if="!selectedItems.length" class="placeholder">
              {{ placeholder }}
            </span>
          </template>
          <template v-else>
            {{ selectedLabel || placeholder }}
          </template>
        </div>
        <div class="dropdown-indicator"></div>
      </slot>
    </div>

    <!-- 下拉菜单 -->
    <teleport to="body">
      <transition name="dropdown">
        <div
            v-show="isOpen"
            class="dropdown-menu"
            :style="dropdownStyle"
            @click.stop
        >
          <!-- 过滤输入框 -->
          <input
              v-if="filterable"
              v-model="filterText"
              class="filter-input"
              :placeholder="filterPlaceholder"
              @input="handleFilterInput"
          />

          <!-- 选项列表 -->
          <div class="options-list" ref="listRef">
            <template v-for="(option, index) in filteredOptions" :key="index">
              <!-- 分组处理 -->
              <div
                  v-if="option.group"
                  class="option-group"
              >
                <slot name="group" :group="option">
                  <div class="group-label">{{ option.group }}</div>
                </slot>
                <div
                    v-for="(item, i) in option.items"
                    :key="i"
                    class="option-item"
                    :class="{
                    selected: isSelected(item),
                    disabled: item.disabled
                  }"
                    @click="selectOption(item)"
                >
                  <slot name="option" :option="item">
                    {{ getOptionLabel(item) }}
                  </slot>
                </div>
              </div>
              <!-- 普通选项 -->
              <div
                  v-else
                  class="option-item"
                  :class="{
                  selected: isSelected(option),
                  disabled: option.disabled
                }"
                  @click="selectOption(option)"
              >
                <slot name="option" :option="option">
                  {{ getOptionLabel(option) }}
                </slot>
              </div>
            </template>
          </div>
        </div>
      </transition>
    </teleport>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  modelValue: [String, Number, Array, Object],
  options: {
    type: Array,
    default: () => []
  },
  optionLabel: {
    type: String,
    default: 'label'
  },
  optionValue: {
    type: String,
    default: 'value'
  },
  placeholder: String,
  disabled: Boolean,
  readonly: Boolean,
  size: {
    type: String,
    validator: v => ['small', 'medium', 'large'].includes(v),
    default: 'medium'
  },
  multiple: Boolean,
  maxSelected: Number,
  dropdownStyle: [Object, String],
  inputStyle: [Object, String],
  filterable: Boolean,
  filterPlaceholder: String
})

const emit = defineEmits([
  'update:modelValue',
  'change',
  'open',
  'close',
  'filter'
])

const isOpen = ref(false)
const filterText = ref('')
const listRef = ref(null)

// 计算选中项
const selectedValue = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

// 处理选项显示标签
const getOptionLabel = option => {
  if (typeof option === 'object') {
    return option[props.optionLabel] || option.label || option.value
  }
  return option
}

// 处理选项实际值
const getOptionValue = option => {
  if (typeof option === 'object') {
    return option[props.optionValue] || option.value
  }
  return option
}

// 当前选中的选项对象
const selectedItems = computed(() => {
  if (!selectedValue.value) return []
  if (props.multiple) {
    return props.options.filter(opt =>
        selectedValue.value.includes(getOptionValue(opt))
    )
  }
  return props.options.find(opt =>
      getOptionValue(opt) === selectedValue.value
  )
})

// 当前显示标签(单选时)
const selectedLabel = computed(() => {
  if (props.multiple) return ''
  return selectedItems.value ? getOptionLabel(selectedItems.value) : ''
})

// 过滤后的选项
const filteredOptions = computed(() => {
  if (!props.filterable || !filterText.value) return props.options
  return props.options.filter(option => {
    const label = getOptionLabel(option).toLowerCase()
    return label.includes(filterText.value.toLowerCase())
  })
})

// 判断选项是否被选中
const isSelected = option => {
  if (props.multiple) {
    return selectedValue.value.includes(getOptionValue(option))
  }
  return getOptionValue(option) === selectedValue.value
}

// 切换下拉框
const toggleDropdown = () => {
  if (props.disabled || props.readonly) return
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    emit('open')
  } else {
    emit('close')
  }
}

// 选择选项
const selectOption = option => {
  if (option.disabled) return

  const value = getOptionValue(option)

  if (props.multiple) {
    const current = Array.isArray(selectedValue.value)
        ? selectedValue.value
        : []
    const index = current.indexOf(value)

    if (index > -1) {
      current.splice(index, 1)
    } else {
      if (props.maxSelected && current.length >= props.maxSelected) return
      current.push(value)
    }
    selectedValue.value = [...current]
  } else {
    selectedValue.value = value
    isOpen.value = false
  }

  emit('change', selectedValue.value)
}

// 移除标签(多选时)
const removeTag = item => {
  if (props.disabled || props.readonly) return
  const value = getOptionValue(item)
  selectedValue.value = selectedValue.value.filter(v => v !== value)
}

// 处理过滤输入
const handleFilterInput = e => {
  emit('filter', e.target.value)
}

// 处理键盘事件
const handleTriggerKeydown = e => {
  if (props.disabled || props.readonly) return

  switch(e.key) {
    case 'ArrowDown':
    case 'Enter':
      isOpen.value = true
      e.preventDefault()
      break
    case 'Escape':
      isOpen.value = false
      break
  }
}

// 点击外部关闭
const clickOutsideHandler = e => {
  if (!isOpen.value) return
  if (!e.target.closest('.dropdown-select')) {
    isOpen.value = false
    emit('close')
  }
}

// 生命周期
onMounted(() => {
  document.addEventListener('click', clickOutsideHandler)
})

onUnmounted(() => {
  document.removeEventListener('click', clickOutsideHandler)
})
</script>

<style scoped>
/* 这里需要添加详细的样式代码 */
.dropdown-select {
  position: relative;
  width: 100%;
  max-width: 300px;
}
.select-trigger {
  border: 1px solid #ccc;
  padding: 8px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dropdown-menu {
  position: absolute;
  border: 1px solid #ccc;
  background: white;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
}
.option-item {
  padding: 8px;
  cursor: pointer;
}
.option-item:hover {
  background: #f0f0f0;
}
.selected {
  background: #e0f0ff;
}
.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>

📚测试代码正常跑通,附其他基本代码

  • 添加路由
  • 页面展示入口

📘编写路由 \src\router\index.js

\router\index.js

import { createRouter, createWebHistory } from 'vue-router'
import RightClickMenuView from '../views/RightClickMenuView.vue'
import RangePickerView from '../views/RangePickerView.vue'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'progress',
      component:  () => import('../views/ProgressView.vue'),
    },
    {
      path: '/tabs',
      name: 'tabs',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      // 标签页(Tabs)
      component: () => import('../views/TabsView.vue'),
    },
    {
      path: '/accordion',
      name: 'accordion',
      // 折叠面板(Accordion)
      component: () => import('../views/AccordionView.vue'),
    },
    {
      path: '/timeline',
      name: 'timeline',
      // 时间线(Timeline)
      component: () => import('../views/TimelineView.vue'),
    },
    {
      path: '/backToTop',
      name: 'backToTop',
      component: () => import('../views/BackToTopView.vue')
    },
    {
      path: '/notification',
      name: 'notification',
      component: () => import('../views/NotificationView.vue')
    },
    {
      path: '/card',
      name: 'card',
      component: () => import('../views/CardView.vue')
    },
    {
      path: '/infiniteScroll',
      name: 'infiniteScroll',
      component: () => import('../views/InfiniteScrollView.vue')
    },
    {
      path: '/switch',
      name: 'switch',
      component: () => import('../views/SwitchView.vue')
    },
    {
      path: '/sidebar',
      name: 'sidebar',
      component: () => import('../views/SidebarView.vue')
    },
    {
      path: '/breadcrumbs',
      name: 'breadcrumbs',
      component: () => import('../views/BreadcrumbsView.vue')
    },
    {
      path: '/masonryLayout',
      name: 'masonryLayout',
      component: () => import('../views/MasonryLayoutView.vue')
    },
    {
      path: '/rating',
      name: 'rating',
      component: () => import('../views/RatingView.vue')
    },
    {
      path: '/datePicker',
      name: 'datePicker',
      component: () => import('../views/DatePickerView.vue')
    },
    {
      path: '/colorPicker',
      name: 'colorPicker',
      component: () => import('../views/ColorPickerView.vue')
    },
    {
      path: '/rightClickMenu',
      name: 'rightClickMenu',
      component: RightClickMenuView
    },
    {
      path: '/rangePicker',
      name: 'rangePicker',
      component: () => import('../views/RangePickerView.vue')
    },
    {
      path: '/navbar',
      name: 'navbar',
      component: () => import('../views/NavbarView.vue')
    },
    {
      path: '/formValidation',
      name: 'formValidation',
      component: () => import('../views/FormValidationView.vue')
    },
    {
      path: '/copyToClipboard',
      name: 'copyToClipboard',
      component: () => import('../views/CopyToClipboardView.vue')
    },
    {
      path: '/clickAnimations',
      name: 'clickAnimations',
      component: () => import('../views/ClickAnimationsView.vue')
    },
    {
      path: '/thumbnailList',
      name: 'thumbnailList',
      component: () => import('../views/ThumbnailListView.vue')
    },
    {
      path: '/keyboardShortcuts',
      name: 'keyboardShortcuts',
      component: () => import('../views/KeyboardShortcutsView.vue')
    },
    {
      path: '/commentSystem',
      name: 'commentSystem',
      component: () => import('../views/CommentSystemView.vue')
    },
    {
      path: '/qRCode',
      name: 'qRCode',
      component: () => import('../views/QRCodeView.vue')
    },
    {
      path: '/radioButton',
      name: 'radioButton',
      component: () => import('../views/RadioButtonView.vue')
    },
    {
      path: '/slider',
      name: 'slider',
      component: () => import('../views/SliderView.vue')
    },
    {
      path: '/scrollAnimations',
      name: 'scrollAnimations',
      component: () => import('../views/ScrollAnimationsView.vue')
    },
    {
      path: '/textInputView',
      name: 'textInputView',
      component: () => import('../views/TextInputView.vue')
    },
    {
      path: '/divider',
      name: 'divider',
      component: () => import('../views/DividerView.vue')
    },
    {
      path: '/checkbox',
      name: 'checkbox',
      component: () => import('../views/CheckboxView.vue')
    },
    {
      path: '/tagInput',
      name: 'tagInput',
      component: () => import('../views/TagInputView.vue')
    },
    {
      path: '/dropdownSelect',
      name: 'dropdownSelect',
      component: () => import('../views/DropdownSelectView.vue')
    }
  ],
})

export default router

📘编写展示入口 \src\App.vue

 src\App.vue

<script setup>
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />
      <nav>
        <RouterLink to="/">Progress</RouterLink>
        <RouterLink to="/tabs">Tabs</RouterLink>
        <RouterLink to="/accordion">Accordion</RouterLink>
        <RouterLink to="/timeline">Timeline</RouterLink>
        <RouterLink to="/backToTop">BackToTop</RouterLink>
        <RouterLink to="/notification">Notification</RouterLink>
        <RouterLink to="/card">Card</RouterLink>
        <RouterLink to="/infiniteScroll">InfiniteScroll</RouterLink>
        <RouterLink to="/switch">Switch</RouterLink>
        <RouterLink to="/sidebar">Sidebar</RouterLink>
        <RouterLink to="/breadcrumbs">Breadcrumbs</RouterLink>
        <RouterLink to="/masonryLayout">MasonryLayout</RouterLink>
        <RouterLink to="/rating">Rating</RouterLink>
        <RouterLink to="/datePicker">DatePicker</RouterLink>
        <RouterLink to="/colorPicker">ColorPicker</RouterLink>
        <RouterLink to="/rightClickMenu">RightClickMenu</RouterLink>
        <RouterLink to="/rangePicker">RangePicker</RouterLink>
        <RouterLink to="/navbar">Navbar</RouterLink>
        <RouterLink to="/formValidation">FormValidation</RouterLink>
        <RouterLink to="/copyToClipboard">CopyToClipboard</RouterLink>
        <RouterLink to="/clickAnimations">ClickAnimations</RouterLink>
        <RouterLink to="/thumbnailList">ThumbnailList</RouterLink>
        <RouterLink to="/keyboardShortcuts">KeyboardShortcuts</RouterLink>
        <RouterLink to="/commentSystem">CommentSystem</RouterLink>
        <RouterLink to="/qRCode">QRCode</RouterLink>
        <RouterLink to="/radioButton">RadioButton</RouterLink>
        <RouterLink to="/slider">Slider</RouterLink>
        <RouterLink to="/scrollAnimations">ScrollAnimations</RouterLink>
        <RouterLink to="/textInputView">TextInput</RouterLink>
        <RouterLink to="/divider">Divider</RouterLink>
        <RouterLink to="/checkbox">Checkbox</RouterLink>
        <RouterLink to="/tagInput">TagInput</RouterLink>
        <RouterLink to="/dropdownSelect">DropdownSelect</RouterLink>
      </nav>
    </div>
  </header>

  <RouterView />
</template>

<style scoped>
header {
  line-height: 1.5;
  max-height: 100vh;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

nav {
  width: 100%;
  font-size: 12px;
  text-align: center;
  margin-top: 2rem;
}

nav a.router-link-exact-active {
  color: var(--color-text);
}

nav a.router-link-exact-active:hover {
  background-color: transparent;
}

nav a {
  display: inline-block;
  padding: 0 1rem;
  border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
  border: 0;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }

  nav {
    text-align: left;
    margin-left: -1rem;
    font-size: 1rem;

    padding: 1rem 0;
    margin-top: 1rem;
  }
}
</style>

📚页面效果

DeepSeek 助力 Vue3 开发:打造丝滑的下拉选择框(Dropdown Select)页面效果

📚相关文章

 

———— 相 关 文 章 ————

 

  1. DeepSeek 助力 Vue 开发:打造丝滑的右键菜单(RightClickMenu)https://blog.csdn.net/qq_33650655/article/details/145706658

  2. DeepSeek 助力 Vue 开发:打造丝滑的范围选择器(Range Picker)https://blog.csdn.net/qq_33650655/article/details/145713572

  3. DeepSeek 助力 Vue 开发:打造丝滑的导航栏(Navbar)https://blog.csdn.net/qq_33650655/article/details/145732421

  4. DeepSeek 助力 Vue 开发:打造丝滑的表单验证(Form Validation)https://blog.csdn.net/qq_33650655/article/details/145735582

  5. DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)https://blog.csdn.net/qq_33650655/article/details/145739569

  6. DeepSeek 助力 Vue 开发:打造丝滑的点击动画(Click Animations)https://blog.csdn.net/qq_33650655/article/details/145766184

  7. DeepSeek 助力 Vue 开发:打造丝滑的缩略图列表(Thumbnail List)https://blog.csdn.net/qq_33650655/article/details/145776679

  8. DeepSeek 助力 Vue 开发:打造丝滑的 键盘快捷键(Keyboard Shortcuts) https://blog.csdn.net/qq_33650655/article/details/145780227

  9. DeepSeek 助力 Vue 开发:打造丝滑的评论系统(Comment System)https://blog.csdn.net/qq_33650655/article/details/145781104

  10. DeepSeek 助力 Vue 开发:打造丝滑的二维码生成(QR Code)https://blog.csdn.net/qq_33650655/article/details/145797928

  11. DeepSeek 助力 Vue 开发:打造丝滑的单选按钮(Radio Button)https://blog.csdn.net/qq_33650655/article/details/145810620

  12. DeepSeek 助力 Vue 开发:打造丝滑的滑块(Slider)https://blog.csdn.net/qq_33650655/article/details/145817161

  13. DeepSeek 助力 Vue 开发:打造丝滑的滚动动画(Scroll Animations)https://blog.csdn.net/qq_33650655/article/details/145818571

  14. DeepSeek 助力 Vue 开发:打造丝滑的文本输入框(Text Input)https://blog.csdn.net/qq_33650655/article/details/145837003

  15. DeepSeek 助力 Vue 开发:打造丝滑的分割线(Divider)https://blog.csdn.net/qq_33650655/article/details/145849100

  16. DeepSeek 助力 Vue 开发:打造丝滑的 复选框(Checkbox)https://blog.csdn.net/qq_33650655/article/details/145855695

  17. DeepSeek 助力 Vue3 开发:打造丝滑的标签输入(Tag Input)https://blog.csdn.net/qq_33650655/article/details/145858574

到此这篇文章就介绍到这了,更多精彩内容请关注本人以前的文章或继续浏览下面的文章,创作不易,如果能帮助到大家,希望大家多多支持宝码香车~💕,若转载本文,一定注明本文链接。


整理不易,点赞关注宝码香车

更多专栏订阅推荐:
👍 html+css+js 绚丽效果
💕 vue
✈️ Electron
⭐️ js
📝 字符串
✍️ 时间对象(Date())操作


http://www.kler.cn/a/562949.html

相关文章:

  • DOM编程
  • 静态库和动态库的制作
  • kafka-leader -1问题解决
  • 索提诺比率(Sortino Ratio):更精准的风险调整收益指标(中英双语)
  • SLAM文献之-IMLS-SLAM: scan-to-model matching based on 3D data
  • Pytorch使用手册—使用TACOTRON2进行文本到语音转换(专题二十四)
  • 二分法 ──── 算法3
  • Spring Boot @Component注解介绍
  • angular轮播图
  • git拉取远程分支到本地分支
  • 第6章 数据工程(二)
  • 【华为OD机考】华为OD笔试真题解析(14)--开心消消乐
  • ComfyUI:Stable Diffusion 及 LoRA、VAE 、ControlNet模型解析
  • 洛谷每日1题-------Day4__陶陶摘苹果
  • 免费使用SCI润色神器QuillBot
  • 软件工程----敏捷模型
  • 岳阳市美术馆预约平台(小程序论文源码调试讲解)
  • Java基础关键_012_包装类
  • WPF10绑定属性
  • 重启 nginx