当前位置:首页 > 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中实现右下角弹框,通常需要结合CSS定位和Vue的组件化特性。弹框可以通过绝对定位固定在右下角,并通过Vue控制其显示与隐藏。 创建弹框组件 新建一个Vue组件(如…

vue实现钟表

vue实现钟表

使用 Vue 实现动态钟表 以下是一个基于 Vue 3 的动态钟表实现方案,包含时分秒指针和数字时间显示。 模板部分 <template> <div class="clock-…

vue实现闪烁

vue实现闪烁

Vue实现元素闪烁效果 使用CSS动画实现 通过Vue绑定class结合CSS动画实现闪烁效果,代码简洁且性能较好。 <template> <div :class="{…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue实现pwa

vue实现pwa

Vue 实现 PWA 的步骤 Vue 结合 PWA(Progressive Web App)可以创建离线可用的 Web 应用。以下是实现方法: 安装 Vue CLI 并创建项目 确保已安装 Vue…

vue实现树目录

vue实现树目录

Vue 实现树形目录 在 Vue 中实现树形目录可以通过递归组件或第三方库(如 element-ui 的 el-tree)完成。以下是两种常见实现方式: 递归组件实现 递归组件适合自定义程度高的树形…