当前位置:首页 > VUE

vue实现搜索框功能

2026-01-21 22:04:04VUE

实现基础搜索框功能

在Vue中实现搜索框功能需要结合v-model进行数据绑定,并监听输入事件。以下是一个基础实现:

<template>
  <div>
    <input 
      type="text" 
      v-model="searchQuery" 
      placeholder="搜索..."
      @input="handleSearch"
    />
    <ul v-if="filteredItems.length">
      <li v-for="item in filteredItems" :key="item.id">
        {{ item.name }}
      </li>
    </ul>
    <p v-else>无匹配结果</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [
        { id: 1, name: '苹果' },
        { id: 2, name: '香蕉' },
        { id: 3, name: '橙子' }
      ],
      filteredItems: []
    }
  },
  methods: {
    handleSearch() {
      this.filteredItems = this.items.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

添加防抖优化性能

频繁触发搜索会影响性能,可以使用防抖技术优化:

vue实现搜索框功能

import { debounce } from 'lodash'

export default {
  methods: {
    handleSearch: debounce(function() {
      this.filteredItems = this.items.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }, 300)
  }
}

实现异步搜索

当需要从API获取搜索结果时:

export default {
  methods: {
    async handleSearch() {
      if (!this.searchQuery.trim()) {
        this.searchResults = []
        return
      }

      try {
        const response = await axios.get('/api/search', {
          params: { q: this.searchQuery }
        })
        this.searchResults = response.data
      } catch (error) {
        console.error('搜索失败:', error)
      }
    }
  }
}

添加搜索建议

实现搜索建议功能可以提升用户体验:

vue实现搜索框功能

<template>
  <div class="search-container">
    <input
      v-model="searchQuery"
      @input="showSuggestions = true"
      @blur="hideSuggestions"
      placeholder="输入搜索内容"
    />
    <ul v-show="showSuggestions && suggestions.length" class="suggestions">
      <li 
        v-for="suggestion in suggestions" 
        :key="suggestion"
        @mousedown="selectSuggestion(suggestion)"
      >
        {{ suggestion }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      showSuggestions: false,
      suggestions: ['苹果', '香蕉', '橙子', '西瓜']
    }
  },
  methods: {
    hideSuggestions() {
      setTimeout(() => {
        this.showSuggestions = false
      }, 200)
    },
    selectSuggestion(suggestion) {
      this.searchQuery = suggestion
      this.showSuggestions = false
      this.performSearch()
    }
  }
}
</script>

样式优化

为搜索框添加基本样式:

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

input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.suggestions {
  position: absolute;
  width: 100%;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ddd;
  border-top: none;
  background: white;
  list-style: none;
  padding: 0;
  margin: 0;
}

.suggestions li {
  padding: 8px;
  cursor: pointer;
}

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

使用计算属性优化

对于本地数据搜索,可以使用计算属性替代方法:

export default {
  computed: {
    filteredItems() {
      return this.items.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}

标签: 功能vue
分享给朋友:

相关文章

vue实现走势图

vue实现走势图

Vue 实现走势图的方法 使用 ECharts 库 ECharts 是一个强大的数据可视化库,支持多种图表类型,包括走势图(折线图)。在 Vue 项目中可以通过 vue-echarts 封装库或直接使…

vue实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="we…

vue实现下拉框删除

vue实现下拉框删除

Vue 实现下拉框删除功能 在Vue中实现下拉框的删除功能通常涉及以下步骤: 数据绑定与渲染 在Vue组件中定义数据数组用于存储下拉框选项: data() { return { op…

vue实现一个tab栏

vue实现一个tab栏

Vue 实现 Tab 栏 基础实现(选项式 API) <template> <div class="tab-container"> <div class="t…

vue实现分屏

vue实现分屏

Vue 实现分屏的方法 分屏功能通常用于展示多个独立内容区域,以下是几种常见的实现方式: 使用 CSS Grid 布局 通过 CSS Grid 可以轻松创建分屏布局,在 Vue 组件中直接应用样式…

vue实现mvc

vue实现mvc

Vue 实现 MVC 模式 Vue 本身是一个 MVVM(Model-View-ViewModel)框架,但可以通过结构调整实现 MVC(Model-View-Controller)模式。以下是具体实…