当前位置:首页 > VUE

使用vue实现搜索

2026-02-10 18:57:13VUE

实现搜索功能的基本步骤

在Vue中实现搜索功能,可以通过v-model绑定输入框,结合计算属性或方法对数据进行过滤。

模板部分

<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实现搜索

对于更复杂的搜索逻辑,可以使用watch来监听搜索词的变化。

使用vue实现搜索

<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>

异步搜索实现

当需要从API获取搜索结果时,可以使用异步方法。

<script>
export default {
  data() {
    return {
      searchQuery: '',
      searchResults: [],
      isLoading: false
    }
  },
  methods: {
    async search() {
      if (this.searchQuery.length < 2) return

      this.isLoading = true
      try {
        const response = await fetch(`/api/search?q=${this.searchQuery}`)
        this.searchResults = await response.json()
      } catch (error) {
        console.error('搜索出错:', error)
      } finally {
        this.isLoading = false
      }
    }
  },
  watch: {
    searchQuery: {
      handler: 'search',
      immediate: false,
      debounce: 300
    }
  }
}
</script>

使用第三方库实现高级搜索

对于更复杂的搜索需求,可以考虑使用第三方库如Fuse.js实现模糊搜索。

安装Fuse.js:

使用vue实现搜索

npm install fuse.js

使用示例:

<script>
import Fuse from 'fuse.js'

export default {
  data() {
    return {
      searchQuery: '',
      items: [
        { id: 1, name: '苹果', category: '水果' },
        { id: 2, name: '胡萝卜', category: '蔬菜' },
        { id: 3, name: '香蕉', category: '水果' }
      ],
      fuse: null,
      searchResults: []
    }
  },
  created() {
    const options = {
      keys: ['name', 'category'],
      threshold: 0.4
    }
    this.fuse = new Fuse(this.items, options)
  },
  watch: {
    searchQuery(newVal) {
      this.searchResults = newVal 
        ? this.fuse.search(newVal).map(r => r.item) 
        : [...this.items]
    }
  }
}
</script>

搜索功能优化建议

添加防抖功能可以减少频繁搜索请求。可以使用lodash的debounce方法或Vue的watch选项。

import { debounce } from 'lodash'

export default {
  methods: {
    search: debounce(function() {
      // 搜索逻辑
    }, 300)
  }
}

为搜索框添加加载状态和空状态提示可以提升用户体验。

<template>
  <div>
    <input 
      v-model="searchQuery" 
      placeholder="搜索..."
      @input="onSearchInput"
    >
    <div v-if="isLoading">搜索中...</div>
    <div v-else-if="searchResults.length === 0 && searchQuery">
      没有找到匹配的结果
    </div>
    <ul v-else>
      <li v-for="item in searchResults" :key="item.id">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

标签: vue
分享给朋友:

相关文章

vue   实现单选

vue 实现单选

Vue 实现单选功能 在 Vue 中实现单选功能可以通过多种方式,以下是几种常见的方法: 使用原生 <input type="radio"> 绑定 v-model 通过 v-model…

vue实现点击

vue实现点击

实现点击事件的基本方法 在Vue中实现点击事件可以通过v-on指令或@简写方式绑定。以下是常见的点击事件绑定方法: <template> <button v-on:click…

vue实现xss

vue实现xss

XSS 攻击简介 XSS(跨站脚本攻击)是一种常见的安全漏洞,攻击者通过注入恶意脚本到网页中,当其他用户访问该页面时,脚本会在其浏览器中执行,可能导致数据泄露或会话劫持。 Vue 中的 XSS…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

vue实现海报

vue实现海报

Vue 实现海报生成方案 使用 html2canvas 库 html2canvas 是一个将 HTML 元素转换为 Canvas 的库,适合将 Vue 组件渲染为海报图片 安装依赖: npm in…

利用vue 实现

利用vue 实现

以下是利用 Vue 实现常见功能的几种方法,分为不同场景和技术要点: 数据绑定与响应式更新 Vue 的核心特性是数据绑定,通过 v-model 实现双向绑定: <template>…