当前位置:首页 > VUE

vue中实现模糊查询

2026-01-23 05:01:23VUE

实现模糊查询的方法

在Vue中实现模糊查询通常需要结合输入框的监听和数组过滤功能。以下是几种常见的实现方式:

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等专门库:

vue中实现模糊查询

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如何实现注册

vue如何实现注册

实现用户注册功能 在Vue中实现注册功能通常需要结合前端表单和后端API交互。以下是完整的实现方案: 创建注册表单组件 注册表单需要包含用户名、邮箱、密码等基本字段,并进行表单验证: <…

vue前端实现搜索

vue前端实现搜索

实现搜索功能的基本方法 在Vue中实现搜索功能通常涉及以下几个关键步骤,结合数据绑定、计算属性和方法调用来动态过滤和显示结果。 数据绑定与输入处理 使用v-model双向绑定搜索输入框的值,监听用户…

vue页面分离的实现

vue页面分离的实现

Vue页面分离的实现方法 将Vue页面分离为多个组件或模块,有助于提升代码可维护性和复用性。以下是几种常见的实现方式: 组件化拆分 通过将页面拆分为多个子组件,每个组件负责特定功能或UI部分。使用…

vue实现表格多行修改

vue实现表格多行修改

实现多行编辑表格 在Vue中实现表格的多行编辑功能,可以通过以下方法完成。这里以Element UI的表格组件为例,但思路适用于其他UI库或原生实现。 数据准备 定义表格数据和编辑状态管理变量:…

vue实现列表显示

vue实现列表显示

Vue 实现列表显示的方法 在 Vue 中实现列表显示通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式。 基本列表渲染 通过 v-for 指令遍历数组,动态生成列…