当前位置:首页 > VUE

vue实现搜索列表

2026-02-11 03:36:38VUE

Vue实现搜索列表的方法

数据绑定与列表渲染

使用v-model绑定搜索输入框,通过v-for渲染列表。示例代码:

<template>
  <input v-model="searchQuery" placeholder="搜索...">
  <ul>
    <li v-for="item in filteredList" :key="item.id">
      {{ item.name }}
    </li>
  </ul>
</template>

计算属性处理过滤逻辑

通过计算属性filteredList实现实时搜索过滤:

vue实现搜索列表

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

数据准备

data中初始化数据和搜索词:

data() {
  return {
    searchQuery: '',
    items: [
      { id: 1, name: '苹果' },
      { id: 2, name: '香蕉' }
    ]
  }
}

异步数据加载

结合axios实现异步数据获取:

vue实现搜索列表

methods: {
  async fetchData() {
    const response = await axios.get('/api/items')
    this.items = response.data
  }
},
created() {
  this.fetchData()
}

性能优化

对于大数据量场景,可添加防抖处理:

import { debounce } from 'lodash'
methods: {
  search: debounce(function() {
    // 过滤逻辑
  }, 300)
}

样式增强

添加加载状态和空状态提示:

<template>
  <div v-if="loading">加载中...</div>
  <div v-else-if="filteredList.length === 0">无匹配结果</div>
</template>

完整组件示例

<template>
  <div>
    <input 
      v-model="searchQuery" 
      @input="handleSearch"
      placeholder="输入关键词搜索"
    >
    <ul v-if="!loading">
      <li 
        v-for="item in filteredList" 
        :key="item.id"
        @click="selectItem(item)"
      >
        {{ item.name }} - {{ item.price }}
      </li>
    </ul>
    <p v-if="loading">搜索中...</p>
    <p v-if="!loading && filteredList.length === 0">
      没有找到匹配项
    </p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [],
      loading: false
    }
  },
  computed: {
    filteredList() {
      const query = this.searchQuery.toLowerCase()
      return this.items.filter(item =>
        item.name.toLowerCase().includes(query) ||
        item.description.toLowerCase().includes(query)
      )
    }
  },
  methods: {
    async handleSearch() {
      this.loading = true
      await this.$nextTick()
      this.loading = false
    },
    selectItem(item) {
      this.$emit('item-selected', item)
    }
  }
}
</script>

标签: 列表vue
分享给朋友:

相关文章

vue实现按钮刷新

vue实现按钮刷新

Vue 实现按钮刷新功能 在 Vue 中实现按钮刷新功能可以通过多种方式实现,具体取决于刷新需求是局部刷新还是全局刷新。以下是几种常见的方法: 使用 window.location.reload()…

vue实现好友列表

vue实现好友列表

实现好友列表的Vue组件 数据准备 在Vue组件的data中定义好友列表数据,通常是一个数组对象,每个对象包含好友的基本信息如ID、头像、昵称等。 data() { return { f…

jq 实现 vue

jq 实现 vue

jq 实现 Vue 的核心功能 jq 是一个轻量级的 JavaScript 库,主要用于 DOM 操作和事件处理。虽然它不能完全替代 Vue,但可以通过一些技巧模拟 Vue 的核心功能,如数据绑定、事…

vue 实现直播

vue 实现直播

Vue 实现直播的基本方法 在Vue中实现直播功能,通常需要结合WebRTC、RTMP或HLS等技术。以下是几种常见的实现方式: 使用WebRTC实现实时直播 WebRTC适合低延迟的实时直播场景,…

vue 实现templateurl

vue 实现templateurl

在 Vue 中,templateUrl 是 Angular 中的一个概念,用于指定外部 HTML 文件作为模板。Vue 本身不直接支持 templateUrl,但可以通过以下方法实现类似功能: 使用…

vue实现投票

vue实现投票

Vue实现投票功能 数据准备 在Vue组件的data中定义投票相关数据,包括选项列表和当前选中状态: data() { return { options: [ { id: 1…