当前位置:首页 > VUE

vue实现search组件

2026-01-16 21:52:16VUE

Vue 实现搜索组件

基础实现

创建一个基础的搜索组件需要包含输入框和搜索逻辑。以下是一个简单的实现示例:

<template>
  <div class="search-container">
    <input 
      v-model="searchQuery" 
      @input="handleSearch" 
      placeholder="Search..."
    />
    <ul v-if="filteredItems.length">
      <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: 'Apple' },
        { id: 2, name: 'Banana' },
        { id: 3, name: 'Orange' }
      ],
      filteredItems: []
    }
  },
  methods: {
    handleSearch() {
      this.filteredItems = this.items.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

使用计算属性优化

计算属性可以自动响应依赖变化,避免手动触发搜索:

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [
        { id: 1, name: 'Apple' },
        { id: 2, name: 'Banana' },
        { id: 3, name: 'Orange' }
      ]
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

添加防抖功能

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

<script>
import { debounce } from 'lodash'

export default {
  data() {
    return {
      searchQuery: '',
      filteredItems: []
    }
  },
  created() {
    this.debouncedSearch = debounce(this.doSearch, 300)
  },
  methods: {
    handleSearch() {
      this.debouncedSearch()
    },
    doSearch() {
      // 实际搜索逻辑
      this.filteredItems = this.items.filter(item =>
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

支持异步搜索

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

<script>
export default {
  methods: {
    async handleSearch() {
      if (!this.searchQuery.trim()) return

      try {
        const response = await axios.get('/api/search', {
          params: { q: this.searchQuery }
        })
        this.searchResults = response.data
      } catch (error) {
        console.error('Search failed:', error)
      }
    }
  }
}
</script>

样式优化

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

.search-container {
  position: relative;
}

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

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

li {
  padding: 8px 12px;
  cursor: pointer;
}

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

组件化封装

将搜索功能封装为可复用组件:

<!-- SearchComponent.vue -->
<template>
  <div class="search-component">
    <slot name="input" :search="search">
      <input
        v-model="searchQuery"
        @input="handleSearch"
        :placeholder="placeholder"
      />
    </slot>

    <slot name="results" :results="filteredItems">
      <ul v-if="showResults && filteredItems.length">
        <li 
          v-for="item in filteredItems" 
          :key="getKey(item)"
          @click="selectItem(item)"
        >
          {{ getItemText(item) }}
        </li>
      </ul>
    </slot>
  </div>
</template>

<script>
export default {
  props: {
    items: {
      type: Array,
      required: true
    },
    placeholder: {
      type: String,
      default: 'Search...'
    },
    filterFn: {
      type: Function,
      default: (item, query) => 
        item.text.toLowerCase().includes(query.toLowerCase())
    },
    getKey: {
      type: Function,
      default: item => item.id
    },
    getItemText: {
      type: Function,
      default: item => item.text
    }
  },
  data() {
    return {
      searchQuery: '',
      showResults: false
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item =>
        this.filterFn(item, this.searchQuery)
      )
    }
  },
  methods: {
    handleSearch() {
      this.showResults = true
    },
    selectItem(item) {
      this.$emit('select', item)
      this.showResults = false
      this.searchQuery = this.getItemText(item)
    }
  }
}
</script>

使用示例

<template>
  <SearchComponent 
    :items="products" 
    @select="handleSelect"
    placeholder="Search products..."
  />
</template>

<script>
import SearchComponent from './SearchComponent.vue'

export default {
  components: { SearchComponent },
  data() {
    return {
      products: [
        { id: 1, name: 'Laptop', price: 999 },
        { id: 2, name: 'Phone', price: 699 }
      ]
    }
  },
  methods: {
    handleSelect(product) {
      console.log('Selected:', product)
    }
  }
}
</script>

这些实现方式涵盖了从基础到高级的搜索组件功能,可以根据实际需求选择适合的方案或组合使用。

vue实现search组件

标签: 组件vue
分享给朋友:

相关文章

vue实现导航栏切换

vue实现导航栏切换

Vue实现导航栏切换的方法 使用v-for和v-bind动态渲染导航项 通过v-for循环遍历导航数据数组,结合v-bind动态绑定class或style。当点击导航项时,更新当前选中项的索引或ID。…

vue实现sql操作

vue实现sql操作

在Vue中实现SQL操作通常需要结合后端服务或本地数据库技术,因为前端JavaScript无法直接连接SQL数据库。以下是几种常见的实现方式: 通过API与后端交互 Vue前端通过HTTP请求(如…

vue实现滚动截屏

vue实现滚动截屏

实现滚动截屏的基本思路 滚动截屏通常指对超出可视区域的长页面进行完整截图。在Vue中,可以通过结合DOM操作、Canvas绘制及第三方库实现。以下是具体方法: 使用html2canvas库实现…

vue实现视频会议

vue实现视频会议

使用 Vue 实现视频会议 技术选型 Vue.js 作为前端框架,结合 WebRTC 技术实现实时音视频通信。常用的库包括: peerjs:简化 WebRTC 的点对点连接。 socket.io:用…

vue实现多用户登录

vue实现多用户登录

实现多用户登录的基本思路 在Vue中实现多用户登录通常需要结合后端API完成身份验证,并通过前端路由、状态管理(如Vuex或Pinia)和本地存储(如localStorage)来管理用户会话。以下是关…

vue实现文章锚点定位

vue实现文章锚点定位

实现文章锚点定位的方法 在Vue中实现文章锚点定位可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML锚点 通过HTML的id属性和<a>标签的href属性实现锚点跳转。在Vu…