当前位置:首页 > 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>

计算属性过滤数据

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

vue搜索功能实现

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>

优化性能

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

vue搜索功能实现

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
    })
  }
}

搜索历史记录

添加搜索历史功能:

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组件的d…

vue实现积分

vue实现积分

Vue 实现积分功能 在 Vue 中实现积分功能通常涉及前端展示、交互逻辑以及与后端 API 的通信。以下是常见的实现方法和步骤: 积分展示组件 创建一个积分展示组件,用于显示当前用户的积分。可以使…

vue实现iframe

vue实现iframe

Vue 中实现 iframe 的方法 在 Vue 项目中,可以通过多种方式实现 iframe 的嵌入。以下是几种常见的方法: 使用原生 HTML iframe 标签 直接在 Vue 组件的模板中使用…

vue实现新闻

vue实现新闻

Vue 实现新闻功能 使用 Vue 实现新闻功能通常涉及新闻列表展示、新闻详情页、分类筛选等模块。以下是实现的基本思路和代码示例。 新闻列表展示 通过 Vue 组件展示新闻列表,通常使用 v-for…

vue实现picker

vue实现picker

Vue 实现 Picker 组件的方法 在 Vue 中实现 Picker 组件可以通过多种方式完成,以下是几种常见的实现方法: 使用原生 HTML 和 CSS 实现 通过 Vue 的模板和样式绑定,…

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.conf…