当前位置:首页 > VUE

vue实现搜索下拉

2026-03-08 17:01:56VUE

Vue 实现搜索下拉功能

基础实现思路

使用Vue的v-model绑定输入框数据,结合v-for渲染下拉选项列表。通过监听输入事件触发搜索逻辑,动态显示或隐藏下拉框。

<template>
  <div class="search-dropdown">
    <input 
      v-model="searchText" 
      @input="handleSearch"
      @focus="showDropdown = true"
      placeholder="输入搜索内容"
    />
    <ul v-show="showDropdown && filteredOptions.length">
      <li 
        v-for="item in filteredOptions" 
        :key="item.id"
        @click="selectItem(item)"
      >
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      searchText: '',
      showDropdown: false,
      options: [], // 原始数据
      filteredOptions: [] // 过滤后的数据
    }
  },
  methods: {
    handleSearch() {
      this.filteredOptions = this.options.filter(item => 
        item.name.toLowerCase().includes(this.searchText.toLowerCase())
      )
    },
    selectItem(item) {
      this.searchText = item.name
      this.showDropdown = false
      // 触发选择事件
      this.$emit('select', item)
    }
  }
}
</script>

防抖优化

频繁触发搜索会影响性能,可以使用lodash的debounce函数进行优化。

vue实现搜索下拉

import { debounce } from 'lodash'

export default {
  methods: {
    handleSearch: debounce(function() {
      this.filteredOptions = this.options.filter(item =>
        item.name.toLowerCase().includes(this.searchText.toLowerCase())
      )
    }, 300)
  }
}

键盘导航支持

为提升用户体验,可以添加键盘上下键选择和回车确认功能。

methods: {
  handleKeyDown(e) {
    if (!this.showDropdown) return

    const currentIndex = this.filteredOptions.findIndex(
      item => item.name === this.searchText
    )

    if (e.key === 'ArrowDown') {
      const nextIndex = (currentIndex + 1) % this.filteredOptions.length
      this.searchText = this.filteredOptions[nextIndex].name
    } else if (e.key === 'ArrowUp') {
      const prevIndex = (currentIndex - 1 + this.filteredOptions.length) % this.filteredOptions.length
      this.searchText = this.filteredOptions[prevIndex].name
    } else if (e.key === 'Enter' && currentIndex !== -1) {
      this.selectItem(this.filteredOptions[currentIndex])
    }
  }
}

远程搜索实现

当需要从服务器获取数据时,可以使用axios等库发起请求。

vue实现搜索下拉

methods: {
  handleSearch: debounce(async function() {
    try {
      const response = await axios.get('/api/search', {
        params: { keyword: this.searchText }
      })
      this.filteredOptions = response.data
    } catch (error) {
      console.error('搜索失败:', error)
    }
  }, 500)
}

样式优化

为下拉框添加基础样式提升视觉效果。

.search-dropdown {
  position: relative;
  width: 300px;
}

.search-dropdown ul {
  position: absolute;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  background: white;
  border: 1px solid #ddd;
  list-style: none;
  padding: 0;
  margin: 0;
  z-index: 1000;
}

.search-dropdown li {
  padding: 8px 12px;
  cursor: pointer;
}

.search-dropdown li:hover {
  background-color: #f5f5f5;
}

组件化封装

将功能封装为可复用组件,通过props接收配置项。

props: {
  options: {
    type: Array,
    default: () => []
  },
  placeholder: {
    type: String,
    default: '请输入'
  },
  remote: {
    type: Boolean,
    default: false
  },
  apiUrl: {
    type: String,
    default: ''
  }
}

这些实现方式可以根据实际需求进行组合和调整,构建出符合项目要求的搜索下拉功能。

标签: vue
分享给朋友:

相关文章

vue实现选择分类

vue实现选择分类

Vue 实现选择分类的方法 使用 v-model 绑定选择值 在 Vue 中可以通过 v-model 指令实现双向数据绑定,适用于下拉选择框(<select>)。以下是一个基本示例: &…

vue实现按钮组轮换

vue实现按钮组轮换

实现按钮组轮换的方法 在Vue中实现按钮组轮换效果可以通过动态绑定类和事件处理来完成。以下是一种常见的实现方式: 模板部分 <template> <div class="bu…

vue设计与实现下载

vue设计与实现下载

vue设计与实现电子书下载 《Vue.js设计与实现》是一本深入解析Vue.js框架原理的书籍,由霍春阳(HcySunYang)撰写。以下是获取该资源的常见途径: 正版购买渠道 京东、当当、天猫等…

js实现vue

js实现vue

Vue.js 的基本实现方法 在 JavaScript 中实现 Vue.js 的功能,可以通过直接引入 Vue 库或使用现代构建工具(如 Vite 或 Webpack)。以下是几种常见的实现方式:…

vue实现slider

vue实现slider

Vue 实现 Slider 组件 使用 Vue 实现 Slider 组件可以通过原生开发或借助第三方库。以下是两种常见方法: 原生实现 Slider 创建一个基础的 Slider 组件,通过 v-m…

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基础…