当前位置:首页 > VUE

vue实现搜索框功能

2026-01-21 22:04:04VUE

实现基础搜索框功能

在Vue中实现搜索框功能需要结合v-model进行数据绑定,并监听输入事件。以下是一个基础实现:

<template>
  <div>
    <input 
      type="text" 
      v-model="searchQuery" 
      placeholder="搜索..."
      @input="handleSearch"
    />
    <ul v-if="filteredItems.length">
      <li v-for="item in filteredItems" :key="item.id">
        {{ item.name }}
      </li>
    </ul>
    <p v-else>无匹配结果</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [
        { id: 1, name: '苹果' },
        { id: 2, name: '香蕉' },
        { id: 3, name: '橙子' }
      ],
      filteredItems: []
    }
  },
  methods: {
    handleSearch() {
      this.filteredItems = this.items.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

添加防抖优化性能

频繁触发搜索会影响性能,可以使用防抖技术优化:

vue实现搜索框功能

import { debounce } from 'lodash'

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

实现异步搜索

当需要从API获取搜索结果时:

export default {
  methods: {
    async handleSearch() {
      if (!this.searchQuery.trim()) {
        this.searchResults = []
        return
      }

      try {
        const response = await axios.get('/api/search', {
          params: { q: this.searchQuery }
        })
        this.searchResults = response.data
      } catch (error) {
        console.error('搜索失败:', error)
      }
    }
  }
}

添加搜索建议

实现搜索建议功能可以提升用户体验:

vue实现搜索框功能

<template>
  <div class="search-container">
    <input
      v-model="searchQuery"
      @input="showSuggestions = true"
      @blur="hideSuggestions"
      placeholder="输入搜索内容"
    />
    <ul v-show="showSuggestions && suggestions.length" class="suggestions">
      <li 
        v-for="suggestion in suggestions" 
        :key="suggestion"
        @mousedown="selectSuggestion(suggestion)"
      >
        {{ suggestion }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      showSuggestions: false,
      suggestions: ['苹果', '香蕉', '橙子', '西瓜']
    }
  },
  methods: {
    hideSuggestions() {
      setTimeout(() => {
        this.showSuggestions = false
      }, 200)
    },
    selectSuggestion(suggestion) {
      this.searchQuery = suggestion
      this.showSuggestions = false
      this.performSearch()
    }
  }
}
</script>

样式优化

为搜索框添加基本样式:

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

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

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

.suggestions li {
  padding: 8px;
  cursor: pointer;
}

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

使用计算属性优化

对于本地数据搜索,可以使用计算属性替代方法:

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

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

相关文章

在线脑图 vue 实现

在线脑图 vue 实现

在线脑图 Vue 实现方案 使用开源库实现 推荐使用 mind-elixir 或 jsmind 这类开源库,它们专为脑图设计且支持 Vue 集成。 安装依赖: npm install mind-e…

用vue实现滑动输入条

用vue实现滑动输入条

使用 Vue 实现滑动输入条 使用原生 HTML5 input range 实现 在 Vue 模板中直接使用 <input type="range">,通过 v-model 绑定数据:…

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: <…

vue实现cs

vue实现cs

Vue 实现 CS(Client-Side)渲染的常见方法 Vue.js 是一个用于构建用户界面的渐进式框架,默认采用客户端渲染(CSR)。以下是几种常见的实现方式: 使用 Vue CLI 创建项目…

vue 全景实现

vue 全景实现

Vue 全景实现方案 在Vue中实现全景效果,通常需要结合WebGL或第三方库来处理3D场景渲染。以下是几种常见方法: 使用Three.js库 Three.js是一个强大的WebGL库,适合创建3D…

vue 组件实现

vue 组件实现

Vue 组件实现方法 单文件组件 (SFC) 使用 .vue 文件格式,包含模板、脚本和样式三部分: <template> <div class="example">{{…