当前位置:首页 > VUE

vue实现搜索列表

2026-03-28 13:45:31VUE

实现搜索列表功能

数据绑定与搜索逻辑

在Vue中实现搜索列表功能需要绑定输入框和列表数据,通过计算属性或方法过滤列表。

<template>
  <div>
    <input v-model="searchQuery" placeholder="搜索...">
    <ul>
      <li v-for="item in filteredList" :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: {
    filteredList() {
      return this.items.filter(item => 
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

使用第三方库增强搜索

对于更复杂的搜索需求,可以使用Fuse.js等模糊搜索库。

vue实现搜索列表

import Fuse from 'fuse.js'

export default {
  methods: {
    fuzzySearch() {
      const options = {
        keys: ['name'],
        threshold: 0.4
      }
      const fuse = new Fuse(this.items, options)
      return fuse.search(this.searchQuery)
    }
  }
}

异步搜索实现

当数据需要从API获取时,可以使用异步搜索模式。

vue实现搜索列表

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

性能优化

对于大型数据集,考虑添加防抖功能避免频繁触发搜索。

import { debounce } from 'lodash'

export default {
  created() {
    this.debouncedSearch = debounce(this.fetchResults, 500)
  },
  watch: {
    searchQuery() {
      this.debouncedSearch()
    }
  }
}

样式增强

为搜索结果添加高亮显示功能。

<li v-for="item in filteredList" v-html="highlight(item.name)"></li>

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

<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>

标签: 列表vue
分享给朋友:

相关文章

vue实现添加用户

vue实现添加用户

Vue 实现添加用户功能 数据绑定与表单设计 在 Vue 中实现添加用户功能,首先需要设计一个表单,用于收集用户输入的数据。通过 v-model 实现双向数据绑定,确保表单数据与 Vue 实例中的数据…

vue实现发送值接受值

vue实现发送值接受值

Vue 实现父子组件传值 父组件向子组件传值(props) 父组件通过 v-bind 或简写 : 向子组件传递数据。子组件通过 props 接收数据。 父组件代码: <template&g…

vue实现模块

vue实现模块

Vue 实现模块化的方法 Vue 支持多种模块化开发方式,可以根据项目需求选择适合的方案。 使用单文件组件(SFC) 单文件组件是 Vue 最常用的模块化方式,将模板、脚本和样式封装在一个 .vue…

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.conf…

vue实现pc

vue实现pc

Vue 实现 PC 端应用开发 Vue.js 是一个流行的前端框架,适用于构建 PC 端 Web 应用。以下是关键步骤和最佳实践: 项目初始化 使用 Vue CLI 或 Vite 创建项目:…

vue实现画廊

vue实现画廊

Vue实现画廊的基本方法 使用Vue.js实现画廊功能可以通过多种方式完成,以下是一种常见的实现方案: 安装必要依赖 npm install vue-gallery --save 引入组件并注册…