当前位置:首页 > VUE

vue实现搜索功能

2026-01-19 00:25:41VUE

实现搜索功能的基本思路

在Vue中实现搜索功能通常需要结合数据绑定、事件监听和过滤逻辑。可以通过计算属性或方法对数据进行实时筛选。

使用计算属性实现搜索

通过v-model绑定搜索输入框,利用计算属性过滤数据列表:

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配合防抖:

<script>
import debounce from 'lodash.debounce'

export default {
  data() {
    return {
      searchQuery: '',
      results: [],
      isLoading: false
    }
  },
  watch: {
    searchQuery: debounce(function(newVal) {
      if (newVal) {
        this.fetchResults(newVal)
      } else {
        this.results = []
      }
    }, 500)
  },
  methods: {
    async fetchResults(query) {
      this.isLoading = true
      try {
        const response = await axios.get(`/api/search?q=${query}`)
        this.results = response.data
      } catch (error) {
        console.error(error)
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

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

对于更复杂的搜索需求,可以考虑使用专用搜索库如Fuse.js:

vue实现搜索功能

import Fuse from 'fuse.js'

export default {
  data() {
    return {
      fuse: null,
      searchQuery: '',
      items: [...],
      searchResults: []
    }
  },
  mounted() {
    this.fuse = new Fuse(this.items, {
      keys: ['name', 'description'],
      threshold: 0.4
    })
  },
  watch: {
    searchQuery(val) {
      this.searchResults = val ? this.fuse.search(val) : this.items
    }
  }
}

添加搜索建议功能

实现搜索框自动完成建议:

<template>
  <div class="search-container">
    <input 
      v-model="searchQuery" 
      @input="handleInput"
      @focus="showSuggestions = true"
      @blur="hideSuggestions"
    >
    <ul v-show="showSuggestions && suggestions.length">
      <li 
        v-for="suggestion in suggestions" 
        :key="suggestion.id"
        @mousedown="selectSuggestion(suggestion)"
      >
        {{ suggestion.text }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      showSuggestions: false,
      suggestions: []
    }
  },
  methods: {
    handleInput() {
      if (this.searchQuery.length > 1) {
        this.fetchSuggestions(this.searchQuery)
      } else {
        this.suggestions = []
      }
    },
    hideSuggestions() {
      setTimeout(() => {
        this.showSuggestions = false
      }, 200)
    },
    selectSuggestion(suggestion) {
      this.searchQuery = suggestion.text
      this.showSuggestions = false
    }
  }
}
</script>

样式优化建议

为搜索组件添加基础样式:

.search-container {
  position: relative;
  width: 300px;
}

.search-container input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-container ul {
  position: absolute;
  width: 100%;
  margin: 0;
  padding: 0;
  list-style: none;
  background: white;
  border: 1px solid #eee;
  max-height: 200px;
  overflow-y: auto;
}

.search-container li {
  padding: 8px;
  cursor: pointer;
}

.search-container li:hover {
  background-color: #f5f5f5;
}

标签: 搜索功能vue
分享给朋友:

相关文章

vue实现图片

vue实现图片

Vue 实现图片功能的方法 静态图片引入 在 Vue 项目中,可以通过 src 属性直接引入静态图片。图片通常放在 public 或 assets 目录下。 <template> &…

vue实现vnc

vue实现vnc

Vue 实现 VNC 客户端 在 Vue 项目中实现 VNC 客户端功能,可以通过集成现有的 VNC 客户端库或组件完成。以下是具体实现方法: 安装依赖库 使用 noVNC 或其他 VNC 客户端…

实现vue table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…

vue实现通讯

vue实现通讯

Vue 组件通讯方法 父子组件通讯 父组件向子组件传递数据通过 props,子组件向父组件传递数据通过 $emit 事件。 父组件模板: <child-component :message=…

vue 实现长按

vue 实现长按

实现长按功能的基本思路 在Vue中实现长按功能,通常需要监听元素的mousedown或touchstart事件,启动一个计时器。当用户按住元素超过设定的时间阈值时,触发长按回调函数。如果在时间阈值内触…

vue实现尺子

vue实现尺子

Vue 实现尺子组件 实现一个尺子组件可以通过 Canvas 或纯 CSS 完成。以下是两种常见实现方式: 使用 Canvas 绘制尺子 通过 Canvas 动态绘制刻度线和数字,适合需要高精度或动…