当前位置:首页 > VUE

vue搜索功能实现

2026-01-14 01:49:34VUE

Vue 搜索功能实现

在 Vue 中实现搜索功能通常涉及以下几个关键步骤:

数据绑定与输入监听

使用 v-model 绑定输入框的值到 Vue 实例的数据属性,监听用户输入变化:

<template>
  <input v-model="searchQuery" placeholder="搜索..." />
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [
        { id: 1, name: '苹果' },
        { id: 2, name: '香蕉' },
        { id: 3, name: '橙子' }
      ]
    }
  }
}
</script>

计算属性过滤数据

通过计算属性实时过滤数据,避免直接修改原始数据:

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

列表渲染过滤结果

在模板中渲染过滤后的结果:

<ul>
  <li v-for="item in filteredItems" :key="item.id">
    {{ item.name }}
  </li>
</ul>

优化性能

对于大数据量搜索,可以添加防抖处理:

import { debounce } from 'lodash'

methods: {
  handleSearch: debounce(function() {
    // 执行搜索逻辑
  }, 300)
}

异步搜索实现

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

methods: {
  async searchItems() {
    try {
      const response = await axios.get('/api/items', {
        params: { q: this.searchQuery }
      })
      this.filteredItems = response.data
    } catch (error) {
      console.error(error)
    }
  }
},
watch: {
  searchQuery(newVal) {
    if (newVal.length > 2) {
      this.searchItems()
    }
  }
}

高级搜索功能

实现多条件复合搜索:

computed: {
  filteredItems() {
    return this.items.filter(item => {
      const matchesName = item.name.toLowerCase().includes(
        this.searchQuery.toLowerCase()
      )
      const matchesCategory = this.selectedCategory 
        ? item.category === this.selectedCategory
        : true
      return matchesName && matchesCategory
    })
  }
}

搜索历史记录

添加搜索历史功能:

vue搜索功能实现

data() {
  return {
    searchHistory: []
  }
},
methods: {
  performSearch() {
    if (this.searchQuery.trim()) {
      this.searchHistory.unshift(this.searchQuery)
      // 限制历史记录数量
      if (this.searchHistory.length > 5) {
        this.searchHistory.pop()
      }
    }
  }
}

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

相关文章

vue实现矩阵

vue实现矩阵

Vue 实现矩阵的方法 在 Vue 中实现矩阵操作可以通过多种方式完成,以下是一些常见的方法: 使用二维数组表示矩阵 矩阵可以用二维数组来表示,每个元素对应矩阵中的一个值。在 Vue 的 data…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model="…

vue 实现工具

vue 实现工具

Vue 实现工具的方法 使用 Vue 实现工具功能可以通过多种方式完成,具体取决于工具的类型和需求。以下是几种常见的方法: 组件化实现 创建一个独立的 Vue 组件来封装工具功能。例如,实现一个计…

vue 实现excel

vue 实现excel

Vue 实现 Excel 功能 前端导出 Excel 使用 xlsx 库可以轻松实现前端 Excel 导出功能。安装依赖: npm install xlsx 导出 Excel 示例代码: impo…

vue实现滚屏

vue实现滚屏

实现滚屏的基本方法 在Vue中实现滚屏效果可以通过多种方式完成,常见的有原生JavaScript滚动方法、第三方库或CSS动画。以下是几种常见实现方式: 使用window.scrollTo或Elem…

vue 实现音乐

vue 实现音乐

Vue 实现音乐播放功能 在 Vue 中实现音乐播放功能,可以通过 HTML5 的 <audio> 元素或第三方库如 howler.js 来实现。以下是两种方法的详细步骤: 使用 HTM…