当前位置:首页 > VUE

vue中实现模糊查询

2026-01-23 05:01:23VUE

实现模糊查询的方法

在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监听搜索词变化

<template>
  <!-- 同上 -->
</template>

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

使用第三方库实现更强大的模糊搜索

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

import Fuse from 'fuse.js'

// 在组件中
methods: {
  initFuse() {
    const options = {
      keys: ['name'],
      threshold: 0.4
    }
    this.fuse = new Fuse(this.items, options)
  },
  search() {
    this.filteredItems = this.searchQuery 
      ? this.fuse.search(this.searchQuery).map(r => r.item)
      : this.items
  }
},
created() {
  this.initFuse()
  this.search()
}

实现防抖优化性能

对于频繁触发的搜索,可以添加防抖功能:

import { debounce } from 'lodash'

// 在methods中
search: debounce(function() {
  this.filteredItems = this.items.filter(item =>
    item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
  )
}, 300)

多字段搜索实现

如果需要搜索多个字段,可以修改过滤逻辑:

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

以上方法可以根据具体需求选择使用,计算属性方式适合简单场景,watch方式适合需要额外逻辑的场景,而Fuse.js等库则适合需要高级模糊匹配功能的场景。

vue中实现模糊查询

标签: 模糊vue
分享给朋友:

相关文章

vue实现聊天

vue实现聊天

Vue实现聊天功能 基础项目结构搭建 使用Vue CLI或Vite创建项目,安装必要依赖如socket.io-client或axios(根据通信方式选择)。核心组件通常包括: ChatWindow…

在线脑图 vue 实现

在线脑图 vue 实现

在线脑图 Vue 实现方案 使用开源库实现 推荐使用 mind-elixir 或 jsmind 这类开源库,它们专为脑图设计且支持 Vue 集成。 安装依赖: npm install mind…

vue前端实现打印功能

vue前端实现打印功能

使用Vue实现前端打印功能 在Vue项目中实现打印功能可以通过多种方式完成,以下是几种常见的方法: 使用window.print()方法 这是最简单的打印方式,直接调用浏览器的打印功能。 meth…

vue实现下拉框删除

vue实现下拉框删除

Vue 实现下拉框删除功能 在Vue中实现下拉框的删除功能通常涉及以下步骤: 数据绑定与渲染 在Vue组件中定义数据数组用于存储下拉框选项: data() { return {…

vue 实现复选

vue 实现复选

Vue 实现复选功能 在 Vue 中实现复选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定数组 通过 v-model 绑定一个数组,可以自动收集用户选择的复选框值。…

vue 方法实现

vue 方法实现

在 Vue 中,方法的实现通常通过 methods 选项完成。以下是 Vue 方法实现的核心要点和示例: 基本方法定义 在 Vue 组件中定义方法时,需将函数声明放在 methods 对象内。这些方…