当前位置:首页 > VUE

前端用vue实现搜索

2026-01-22 06:46:20VUE

实现 Vue 搜索功能

数据绑定与输入监听

在 Vue 组件中,使用 v-model 双向绑定搜索输入框的值。通过 @input@keyup 事件监听用户输入变化。

<template>
  <input v-model="searchQuery" @input="handleSearch" placeholder="搜索...">
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [], // 原始数据列表
      filteredItems: [] // 过滤后的结果
    }
  },
  methods: {
    handleSearch() {
      this.filteredItems = this.items.filter(item => 
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

使用计算属性优化性能

对于小型数据集,可以用计算属性替代方法调用,实现自动响应式更新。

前端用vue实现搜索

computed: {
  filteredItems() {
    return this.items.filter(item =>
      item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
    )
  }
}

添加防抖优化

频繁触发搜索时,通过防抖函数减少请求或计算次数。

methods: {
  handleSearch: _.debounce(function() {
    this.filteredItems = this.items.filter(item =>
      item.name.includes(this.searchQuery)
    )
  }, 300)
}

服务端搜索实现

当数据量较大时,需要调用 API 接口进行服务端搜索。

前端用vue实现搜索

methods: {
  async handleSearch() {
    try {
      const response = await axios.get('/api/search', {
        params: { q: this.searchQuery }
      })
      this.filteredItems = response.data
    } catch (error) {
      console.error('搜索出错:', error)
    }
  }
}

高级搜索功能

实现多条件复合搜索,可以结合多个字段进行过滤。

computed: {
  filteredItems() {
    return this.items.filter(item => {
      const matchesName = item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      const matchesCategory = this.selectedCategory ? 
        item.category === this.selectedCategory : true
      return matchesName && matchesCategory
    })
  }
}

搜索结果高亮显示

在渲染搜索结果时,对匹配文本进行高亮处理。

<template>
  <div v-for="item in filteredItems" :key="item.id">
    <span v-html="highlightMatches(item.name)"></span>
  </div>
</template>

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

标签: vue
分享给朋友:

相关文章

vue实现继承语法糖

vue实现继承语法糖

在Vue中实现继承可以通过多种方式模拟类继承的效果,以下是常见的几种方法: 使用mixins实现逻辑复用 通过Vue的mixins机制共享组件选项,达到类似继承的效果: const BaseC…

vue的艾特功能实现

vue的艾特功能实现

Vue 的 @ 功能实现 在 Vue 中实现类似社交平台的 @ 功能,通常涉及输入框的监听、用户匹配和选择插入。以下是具体实现方法: 监听输入框内容 使用 v-model 绑定输入框内容,并通过…

vue SSG实现

vue SSG实现

Vue SSG 实现方法 Vue 的静态站点生成(SSG)可以通过多种工具和框架实现,以下是几种常见的方法: 使用 VuePress VuePress 是一个基于 Vue 的静态站点生成器,适合文档…

vue实现排序

vue实现排序

Vue 实现排序的方法 在 Vue 中实现排序可以通过多种方式完成,以下是一些常见的方法: 使用计算属性排序数组 计算属性非常适合对数据进行排序,因为它会在依赖的数据变化时自动更新。以下是一个示例:…

vue 实现排序

vue 实现排序

Vue 实现排序的方法 使用计算属性实现排序 通过计算属性对数组进行排序,可以保持原始数据不变。示例代码展示了如何对列表按名称升序排序: <template> <div>…

vue实现flbook

vue实现flbook

Vue 实现类似 Flbook 的翻页效果 要实现类似 Flbook 的翻页效果,可以使用 Vue 结合 CSS 动画和 JavaScript 事件处理。以下是实现方法: 安装依赖 需要安装 vu…