当前位置:首页 > VUE

vue 搜索功能实现

2026-03-09 03:51:01VUE

实现搜索功能的基本思路

在Vue中实现搜索功能通常涉及以下几个关键步骤:监听用户输入、过滤数据列表、实时更新显示结果。以下是具体实现方法。

使用v-model绑定输入框

在模板中添加一个输入框,使用v-model双向绑定到Vue实例的数据属性。例如:

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

在脚本中定义searchQuery

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [
        { name: '苹果', category: '水果' },
        { name: '香蕉', category: '水果' },
        { name: '胡萝卜', category: '蔬菜' }
      ]
    }
  }
}
</script>

计算属性过滤数据

利用计算属性实时过滤数据,避免直接修改原始数据。根据searchQuery的内容对items数组进行筛选:

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

显示过滤后的结果

在模板中遍历filteredItems显示搜索结果:

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

多条件搜索实现

若需支持多字段(如名称和分类)搜索,可扩展过滤逻辑:

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

添加防抖优化性能

频繁输入可能引发性能问题,可通过防抖函数限制触发频率:

methods: {
  debounce(fn, delay) {
    let timeout
    return (...args) => {
      clearTimeout(timeout)
      timeout = setTimeout(() => fn.apply(this, args), delay)
    }
  }
},
created() {
  this.debouncedFilter = this.debounce(this.updateFilter, 300)
}

服务端搜索实现

当数据量较大时,建议将搜索逻辑移至服务端:

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

使用第三方库增强功能

对于复杂搜索需求,可考虑使用专门库如Fuse.js实现模糊搜索:

vue 搜索功能实现

import Fuse from 'fuse.js'

computed: {
  fuse() {
    return new Fuse(this.items, {
      keys: ['name', 'category'],
      threshold: 0.4
    })
  },
  filteredItems() {
    return this.searchQuery 
      ? this.fuse.search(this.searchQuery).map(r => r.item)
      : this.items
  }
}

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

相关文章

vue表格重置怎么实现

vue表格重置怎么实现

重置表格数据的方法 在Vue中重置表格数据通常需要操作绑定的数据源,以下是几种常见实现方式: 直接重置数据源 // 假设表格绑定的是tableData this.tableData = [...t…

vue实现ai

vue实现ai

Vue 实现 AI 功能 Vue.js 可以通过集成第三方 AI 服务或本地 AI 模型来实现 AI 功能。以下是几种常见的方法: 集成第三方 AI API 使用 Vue 调用如 OpenAI、Go…

vue element实现

vue element实现

Vue Element UI 实现 Vue Element UI 是基于 Vue.js 的组件库,提供丰富的 UI 组件,适合快速开发企业级中后台产品。以下是一些关键实现方法和步骤: 安装 Vue…

vue实现sso

vue实现sso

Vue 实现 SSO(单点登录)方案 单点登录(SSO)允许用户通过一次登录访问多个相关系统。以下是基于 Vue 的实现方案: 使用 OAuth2/OpenID Connect 协议 OAuth2…

vue实现suspense

vue实现suspense

Vue 3 中实现 Suspense Suspense 是 Vue 3 引入的一个内置组件,用于处理异步依赖的加载状态。它允许在等待异步组件或异步数据加载时显示一个后备内容(fallback),直到异…

vue实现route

vue实现route

Vue 路由实现方法 Vue 中实现路由通常使用 vue-router 库,这是 Vue 官方推荐的路由管理器。以下是具体实现步骤: 安装 vue-router 通过 npm 或 yarn 安装…