当前位置:首页 > 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 购物按钮实现方法 基础按钮实现 使用 Vue 的模板语法创建基础按钮组件,绑定点击事件处理购物逻辑: <template> <button @click="addToC…

vue前端分页怎么实现

vue前端分页怎么实现

前端分页实现方法 在Vue中实现前端分页通常涉及数据分割和页面控制逻辑。以下是常见的实现方式: 使用计算属性分页 通过计算属性对数据进行切片处理: computed: { paginate…

vue实现菜单栏锚点

vue实现菜单栏锚点

实现锚点菜单的基本思路 在Vue中实现菜单栏锚点功能,主要涉及两个方面:创建可跳转的锚点位置,以及菜单项的点击滚动控制。通过监听滚动事件可以高亮当前可见区域的对应菜单项。 创建页面锚点位置 在需要跳…

vue实现轮询

vue实现轮询

实现轮询的基本方法 在Vue中实现轮询可以通过setInterval或setTimeout配合递归调用完成。轮询通常用于定期向服务器请求数据更新。 使用setInterval的简单示例: data…

vue实现点击

vue实现点击

实现点击事件的基本方法 在Vue中实现点击事件可以通过v-on指令或@简写方式绑定。以下是常见的点击事件绑定方法: <template> <button v-on:click=…

vue  select实现

vue select实现

Vue Select 实现方法 在 Vue 中实现下拉选择功能可以使用原生 <select> 标签或第三方库如 vue-select。以下是两种方法的详细说明: 原生 HTML Sele…