当前位置:首页 > VUE

vue 实现模糊搜索

2026-01-18 19:04:24VUE

Vue 实现模糊搜索的方法

使用计算属性实现模糊搜索

在 Vue 中,可以通过计算属性结合 JavaScript 的 filterincludes 方法实现简单的模糊搜索功能。假设有一个数据列表 items 和一个搜索关键词 searchTerm

data() {
  return {
    items: ['Apple', 'Banana', 'Orange', 'Grape'],
    searchTerm: ''
  }
},
computed: {
  filteredItems() {
    return this.items.filter(item => 
      item.toLowerCase().includes(this.searchTerm.toLowerCase())
    )
  }
}

在模板中使用 v-model 绑定搜索框,并展示过滤后的结果:

<input v-model="searchTerm" placeholder="Search...">
<ul>
  <li v-for="item in filteredItems" :key="item">{{ item }}</li>
</ul>

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

对于更复杂的模糊搜索需求,可以使用 fuse.js 这样的专门库:

安装 fuse.js:

vue 实现模糊搜索

npm install fuse.js

在 Vue 组件中使用:

import Fuse from 'fuse.js'

data() {
  return {
    items: [
      { name: 'Apple', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' }
    ],
    searchTerm: '',
    fuse: null
  }
},
created() {
  this.fuse = new Fuse(this.items, {
    keys: ['name', 'category'],
    threshold: 0.4
  })
},
computed: {
  filteredItems() {
    return this.searchTerm 
      ? this.fuse.search(this.searchTerm).map(result => result.item)
      : this.items
  }
}

实现带高亮的模糊搜索

可以扩展模糊搜索功能,在结果中高亮匹配的部分:

methods: {
  highlight(text, query) {
    if (!query) return text
    const regex = new RegExp(`(${query})`, 'gi')
    return text.replace(regex, '<span class="highlight">$1</span>')
  }
}

在模板中使用 v-html 渲染高亮内容:

vue 实现模糊搜索

<li v-for="item in filteredItems" :key="item.name">
  <span v-html="highlight(item.name, searchTerm)"></span>
</li>

使用防抖优化搜索性能

对于大数据集,可以使用防抖技术减少频繁搜索带来的性能问题:

import { debounce } from 'lodash'

methods: {
  debouncedSearch: debounce(function() {
    // 执行搜索逻辑
  }, 300)
}

服务端模糊搜索实现

当数据量很大时,可以考虑将模糊搜索逻辑移至服务端:

methods: {
  async searchItems() {
    const response = await axios.get('/api/items', {
      params: { q: this.searchTerm }
    })
    this.filteredItems = response.data
  }
}

多字段权重搜索

使用 fuse.js 可以设置不同字段的搜索权重:

this.fuse = new Fuse(this.items, {
  keys: [
    { name: 'name', weight: 0.7 },
    { name: 'category', weight: 0.3 }
  ]
})

以上方法可以根据实际需求选择或组合使用,实现从简单到复杂的模糊搜索功能。

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

相关文章

vue实现递归

vue实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身: &…

vue实现分类

vue实现分类

Vue实现分类功能的方法 使用v-for和计算属性 通过计算属性对数据进行分类处理,结合v-for渲染分类后的列表。示例代码: <template> <div>…

vue实现过滤

vue实现过滤

Vue实现过滤的方法 在Vue中实现数据过滤可以通过多种方式完成,以下是几种常见的方法: 使用计算属性过滤 计算属性是Vue中处理数据过滤的理想选择,它们基于响应式依赖进行缓存,只有在相关依赖发生改…

vue页面实现

vue页面实现

Vue 页面实现方法 创建 Vue 组件 使用 Vue 单文件组件(SFC)方式创建页面,文件扩展名为 .vue。一个基本的 Vue 组件包含三个部分:模板(template)、脚本(script)和…

vue 实现过滤

vue 实现过滤

Vue 实现过滤的方法 在 Vue 中实现过滤功能可以通过多种方式完成,包括使用计算属性、自定义过滤器、第三方库等。以下是几种常见的实现方法: 使用计算属性进行过滤 计算属性是 Vue 中最常用的过…

vue实现oauth

vue实现oauth

Vue 实现 OAuth 的步骤 安装必要的依赖 确保项目中安装了 axios 和 vue-router。OAuth 通常需要发送 HTTP 请求和处理路由跳转。 npm install axios…