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

搜索历史记录

添加搜索历史功能:

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 3(Composition API)或 Vue 2(Options API)作为前端框架,搭配 Vue Router 实现路由管理,V…

vue实现前端分离

vue实现前端分离

Vue 实现前后端分离 前后端分离是一种架构模式,前端负责页面渲染和交互逻辑,后端提供数据接口。Vue.js 作为前端框架,非常适合实现前后端分离的开发模式。 核心实现步骤 创建 Vue 项目 使…

vue实现选择分类

vue实现选择分类

Vue 实现选择分类的方法 使用 v-model 绑定选择值 在 Vue 中可以通过 v-model 指令实现双向数据绑定,适用于下拉选择框(<select>)。以下是一个基本示例: &…

vue实现检测数组

vue实现检测数组

Vue 中检测数组变化的方法 Vue 的响应式系统无法直接检测到数组的某些变化,因为 JavaScript 的限制。以下是一些解决方案: 使用 Vue.set 或 this.$set Vue 提供…

拖拽式编程vue实现

拖拽式编程vue实现

拖拽式编程在 Vue 中的实现方法 使用 HTML5 原生拖放 API Vue 可以结合 HTML5 的拖放 API 实现基础拖拽功能。通过 draggable 属性标记可拖拽元素,监听 dragst…

前端多线程实现vue

前端多线程实现vue

前端多线程与Vue的结合 在Vue中实现多线程通常通过Web Worker技术完成。Web Worker允许在后台线程中运行脚本,避免阻塞主线程,适合处理计算密集型任务。 使用Web Worker的…