当前位置:首页 > VUE

vue搜索功能实现

2026-03-07 18:19:12VUE

实现Vue搜索功能的方法

基础搜索实现

在Vue组件中声明一个搜索词数据属性和一个列表数据属性

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())
    )
  }
}

在模板中使用v-model绑定搜索输入框

<input v-model="searchQuery" placeholder="Search...">
<ul>
  <li v-for="item in filteredItems" :key="item.id">
    {{ item.name }}
  </li>
</ul>

高级搜索功能

实现多字段搜索

vue搜索功能实现

computed: {
  filteredItems() {
    const query = this.searchQuery.toLowerCase()
    return this.items.filter(item => 
      item.name.toLowerCase().includes(query) ||
      item.description.toLowerCase().includes(query)
    )
  }
}

添加搜索延迟(防抖)

import _ from 'lodash'

methods: {
  search: _.debounce(function(query) {
    this.searchQuery = query
  }, 500)
}

服务器端搜索

使用axios发送搜索请求

vue搜索功能实现

methods: {
  async searchItems() {
    try {
      const response = await axios.get('/api/items', {
        params: { q: this.searchQuery }
      })
      this.items = response.data
    } catch (error) {
      console.error(error)
    }
  }
}

添加搜索按钮触发

<input v-model="searchQuery" @keyup.enter="searchItems">
<button @click="searchItems">Search</button>

搜索建议实现

添加搜索建议功能

data() {
  return {
    suggestions: [],
    showSuggestions: false
  }
},
methods: {
  async getSuggestions() {
    if(this.searchQuery.length > 2) {
      const response = await axios.get('/api/suggestions', {
        params: { q: this.searchQuery }
      })
      this.suggestions = response.data
      this.showSuggestions = true
    }
  }
}

在模板中显示建议

<ul v-if="showSuggestions && suggestions.length">
  <li 
    v-for="suggestion in suggestions" 
    :key="suggestion.id"
    @click="selectSuggestion(suggestion)"
  >
    {{ suggestion.name }}
  </li>
</ul>

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

相关文章

vue交互实现

vue交互实现

Vue 交互实现方法 Vue.js 提供了多种方式实现用户交互,包括事件处理、表单绑定、动态渲染等。以下是常见的交互实现方法: 事件处理 通过 v-on 或 @ 指令绑定事件,触发方法或直接执行表达…

vue SSG实现

vue SSG实现

Vue SSG 实现方法 Vue 的静态站点生成(SSG)可以通过多种工具和框架实现,以下是几种常见的方法: 使用 VuePress VuePress 是一个基于 Vue 的静态站点生成器,适合文档…

vue router 实现

vue router 实现

Vue Router 的实现 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是 Vue Router 的核心实现方式。 安装 Vue Router 通过…

tabbar 实现 vue

tabbar 实现 vue

在 Vue 中实现 TabBar 功能可以通过多种方式完成,以下是几种常见的方法: 使用 Vue Router 结合自定义组件 创建一个自定义的 TabBar 组件,结合 Vue Route…

vue nexttrick实现

vue nexttrick实现

Vue 中 nextTick 的实现原理 nextTick 是 Vue 提供的一个异步方法,用于在下次 DOM 更新循环结束之后执行延迟回调。它利用了 JavaScript 的事件循环机制,确保回调在…

vue实现伸缩

vue实现伸缩

Vue实现伸缩功能的方法 使用CSS过渡和Vue的v-if或v-show 通过CSS的transition属性结合Vue的条件渲染指令(v-if或v-show)可以实现元素的伸缩效果。定义一个CSS类…