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

多字段搜索实现

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

vue中实现模糊查询

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实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组件…

vue实现单点

vue实现单点

Vue 实现单点登录(SSO)方案 单点登录(SSO)允许用户在多个相关但独立的系统中使用同一组凭证登录。以下是基于 Vue 的实现方案: 基于 OAuth2/OpenID Connect 的实现…

vue实现active

vue实现active

Vue 实现 active 状态的方法 在 Vue 中实现 active 状态可以通过以下几种方式实现,具体取决于使用场景和需求。 使用 v-bind:class 动态绑定类名 通过 v-bind:…

vue实现ajax

vue实现ajax

Vue 中实现 AJAX 的几种方法 在 Vue 中实现 AJAX 请求可以通过原生 JavaScript 的 XMLHttpRequest、第三方库如 axios 或 fetch API 来完成。以…

vue实现mui

vue实现mui

使用 Vue 实现 MUI(Material-UI)风格的界面 Vue 本身不直接提供 MUI(Material Design)组件,但可以通过集成第三方库或手动实现来达到类似效果。以下是几种常见方法…

vue实现复制

vue实现复制

Vue 实现复制功能 在 Vue 中实现复制功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 Clipboard API Clipboard API 是现代浏览器提供的一种原生 AP…