当前位置:首页 > VUE

vue实现搜索功能

2026-01-19 00:25:41VUE

实现搜索功能的基本思路

在Vue中实现搜索功能通常需要结合数据绑定、事件监听和过滤逻辑。可以通过计算属性或方法对数据进行实时筛选。

使用计算属性实现搜索

通过v-model绑定搜索输入框,利用计算属性过滤数据列表:

vue实现搜索功能

<template>
  <div>
    <input v-model="searchQuery" placeholder="搜索...">
    <ul>
      <li v-for="item in filteredItems" :key="item.id">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

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

使用watch实现异步搜索

当需要从API异步获取搜索结果时,可以使用watch配合防抖:

<script>
import debounce from 'lodash.debounce'

export default {
  data() {
    return {
      searchQuery: '',
      results: [],
      isLoading: false
    }
  },
  watch: {
    searchQuery: debounce(function(newVal) {
      if (newVal) {
        this.fetchResults(newVal)
      } else {
        this.results = []
      }
    }, 500)
  },
  methods: {
    async fetchResults(query) {
      this.isLoading = true
      try {
        const response = await axios.get(`/api/search?q=${query}`)
        this.results = response.data
      } catch (error) {
        console.error(error)
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

使用第三方库实现高级搜索

对于更复杂的搜索需求,可以考虑使用专用搜索库如Fuse.js:

vue实现搜索功能

import Fuse from 'fuse.js'

export default {
  data() {
    return {
      fuse: null,
      searchQuery: '',
      items: [...],
      searchResults: []
    }
  },
  mounted() {
    this.fuse = new Fuse(this.items, {
      keys: ['name', 'description'],
      threshold: 0.4
    })
  },
  watch: {
    searchQuery(val) {
      this.searchResults = val ? this.fuse.search(val) : this.items
    }
  }
}

添加搜索建议功能

实现搜索框自动完成建议:

<template>
  <div class="search-container">
    <input 
      v-model="searchQuery" 
      @input="handleInput"
      @focus="showSuggestions = true"
      @blur="hideSuggestions"
    >
    <ul v-show="showSuggestions && suggestions.length">
      <li 
        v-for="suggestion in suggestions" 
        :key="suggestion.id"
        @mousedown="selectSuggestion(suggestion)"
      >
        {{ suggestion.text }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      showSuggestions: false,
      suggestions: []
    }
  },
  methods: {
    handleInput() {
      if (this.searchQuery.length > 1) {
        this.fetchSuggestions(this.searchQuery)
      } else {
        this.suggestions = []
      }
    },
    hideSuggestions() {
      setTimeout(() => {
        this.showSuggestions = false
      }, 200)
    },
    selectSuggestion(suggestion) {
      this.searchQuery = suggestion.text
      this.showSuggestions = false
    }
  }
}
</script>

样式优化建议

为搜索组件添加基础样式:

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

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

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

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

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

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

相关文章

vue如何实现到期提醒

vue如何实现到期提醒

实现 Vue 到期提醒功能 使用计算属性计算剩余时间 在 Vue 组件中定义一个计算属性,计算目标日期与当前日期的差值。通过 Date 对象获取时间戳并计算剩余天数或小时数。 computed:…

vue实现录音文件播放

vue实现录音文件播放

使用 Vue 实现录音文件播放 准备工作 确保项目中已安装必要的依赖,如 vue-audio-recorder 或原生 Web Audio API。录音文件播放通常涉及录音、存储和播放三个核心环节。…

vue实现上移下移插件

vue实现上移下移插件

实现上移下移功能的 Vue 插件 在 Vue 中实现列表项的上移和下移功能,可以通过自定义指令或组件封装的方式完成。以下是两种常见实现方式: 基于数组操作的通用方法 通过操作数组索引实现元素位置交…

vue实现文章锚点定位

vue实现文章锚点定位

实现文章锚点定位的方法 在Vue中实现文章锚点定位可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML锚点 通过HTML的id属性和<a>标签的href属性实现锚点跳转。在V…

vue实现分类

vue实现分类

Vue实现分类功能的方法 使用v-for和计算属性 通过计算属性对数据进行分类处理,结合v-for渲染分类后的列表。示例代码: <template> <div>…

vue 实现闪烁

vue 实现闪烁

Vue 实现闪烁效果的方法 方法一:使用 CSS 动画 在 Vue 组件中定义一个闪烁的 CSS 动画,通过绑定 class 或 style 来控制元素的闪烁效果。 <template&…