当前位置:首页 > VUE

vue怎么实现搜索

2026-02-19 10:02:35VUE

Vue实现搜索功能的方法

在Vue中实现搜索功能通常涉及数据绑定、事件处理和列表过滤。以下是几种常见实现方式:

使用v-model和computed属性实现搜索

通过v-model绑定输入框,利用computed属性过滤数据:

vue怎么实现搜索

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

当需要从API获取搜索结果时,可以使用watch:

<template>
  <div>
    <input v-model="searchQuery" placeholder="搜索...">
    <ul v-if="results.length">
      <li v-for="result in results" :key="result.id">
        {{ result.title }}
      </li>
    </ul>
    <p v-else>无搜索结果</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      results: [],
      timer: null
    }
  },
  watch: {
    searchQuery(newVal) {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.fetchResults(newVal)
      }, 500)
    }
  },
  methods: {
    async fetchResults(query) {
      if (!query.trim()) {
        this.results = []
        return
      }
      const response = await fetch(`/api/search?q=${query}`)
      this.results = await response.json()
    }
  }
}
</script>

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

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

vue怎么实现搜索

<template>
  <div>
    <input v-model="searchTerm" placeholder="模糊搜索...">
    <ul>
      <li v-for="result in searchResults" :key="result.id">
        {{ result.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import Fuse from 'fuse.js'

export default {
  data() {
    return {
      searchTerm: '',
      items: [
        { id: 1, name: 'JavaScript高级程序设计' },
        { id: 2, name: 'Vue.js实战' },
        { id: 3, name: 'React入门' }
      ],
      fuse: null
    }
  },
  computed: {
    searchResults() {
      return this.searchTerm 
        ? this.fuse.search(this.searchTerm).map(r => r.item)
        : this.items
    }
  },
  mounted() {
    this.fuse = new Fuse(this.items, {
      keys: ['name'],
      threshold: 0.4
    })
  }
}
</script>

实现搜索历史功能

可以添加搜索历史记录功能增强用户体验:

<template>
  <div>
    <input 
      v-model="searchInput"
      @keyup.enter="performSearch"
      placeholder="输入搜索内容..."
    >
    <button @click="performSearch">搜索</button>

    <div v-if="searchHistory.length">
      <h3>搜索历史</h3>
      <ul>
        <li 
          v-for="(term, index) in searchHistory" 
          :key="index"
          @click="searchInput = term; performSearch()"
        >
          {{ term }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchInput: '',
      searchHistory: []
    }
  },
  methods: {
    performSearch() {
      if (!this.searchInput.trim()) return

      // 添加到历史记录
      if (!this.searchHistory.includes(this.searchInput)) {
        this.searchHistory.unshift(this.searchInput)
        // 限制历史记录数量
        if (this.searchHistory.length > 5) {
          this.searchHistory.pop()
        }
      }

      // 执行搜索逻辑
      console.log('搜索:', this.searchInput)
    }
  }
}
</script>

实现搜索高亮显示

在搜索结果中高亮显示匹配部分:

<template>
  <div>
    <input v-model="searchText" placeholder="搜索...">
    <ul>
      <li v-for="item in filteredItems" :key="item.id" v-html="highlight(item.text)"></li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchText: '',
      items: [
        { id: 1, text: 'Vue是一款渐进式JavaScript框架' },
        { id: 2, text: 'React由Facebook开发' },
        { id: 3, text: 'Angular是Google的产品' }
      ]
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => 
        this.searchText 
          ? item.text.toLowerCase().includes(this.searchText.toLowerCase())
          : true
      )
    }
  },
  methods: {
    highlight(text) {
      if (!this.searchText) return text
      const regex = new RegExp(this.searchText, '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中实现多级组件通常涉及父子组件嵌套,通过props向下传递数据,通过$emit向上传递事件。多级组件的核心是递归或动态组件渲染。 <!-- 父组件 Parent…

vue实现菜单栏锚点

vue实现菜单栏锚点

实现锚点菜单的基本思路 在Vue中实现菜单栏锚点功能,主要涉及两个方面:创建可跳转的锚点位置,以及菜单项的点击滚动控制。通过监听滚动事件可以高亮当前可见区域的对应菜单项。 创建页面锚点位置 在需要跳…

vue实现剪辑

vue实现剪辑

Vue 实现视频剪辑功能 在Vue中实现视频剪辑功能通常需要结合HTML5的<video>元素和第三方库(如FFmpeg.js或Video.js)。以下是几种常见的实现方法: 使用FFm…

vue实现setinterval

vue实现setinterval

在 Vue 中使用 setInterval Vue 中可以通过生命周期钩子和方法结合 setInterval 实现定时任务。以下是一个完整的实现示例: <template> <…

vue 实现回复

vue 实现回复

Vue 实现回复功能 在 Vue 中实现回复功能通常涉及表单提交、数据绑定和列表渲染。以下是实现步骤和代码示例: 数据绑定与表单 <template> <div>…

vue实现ajax

vue实现ajax

Vue 中实现 AJAX 的几种方法 在 Vue 中实现 AJAX 请求可以通过原生 JavaScript 的 XMLHttpRequest、第三方库如 axios 或 fetch API 来完成。以…