当前位置:首页 > VUE

vue实现搜索自动查询

2026-02-21 06:34:12VUE

Vue实现搜索自动查询

实现搜索自动查询功能通常涉及监听输入框的变化,并在用户输入时触发搜索请求。以下是几种常见的实现方式:

使用v-model和watch监听输入变化

通过v-model绑定输入框的值,并使用watch监听变化,配合防抖函数避免频繁请求。

<template>
  <input v-model="searchQuery" placeholder="搜索...">
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      debounceTimer: null
    }
  },
  watch: {
    searchQuery(newVal) {
      clearTimeout(this.debounceTimer)
      this.debounceTimer = setTimeout(() => {
        this.performSearch(newVal)
      }, 500) // 500ms防抖延迟
    }
  },
  methods: {
    performSearch(query) {
      // 执行搜索API调用
      console.log('正在搜索:', query)
    }
  }
}
</script>

使用计算属性和watch的组合

对于需要更复杂逻辑的情况,可以结合计算属性使用。

<template>
  <input v-model="searchQuery" placeholder="搜索...">
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      searchResults: []
    }
  },
  computed: {
    normalizedQuery() {
      return this.searchQuery.trim().toLowerCase()
    }
  },
  watch: {
    normalizedQuery: {
      handler(newVal) {
        if (newVal.length > 2) { // 至少3个字符才搜索
          this.performSearch(newVal)
        }
      },
      immediate: false
    }
  },
  methods: {
    async performSearch(query) {
      try {
        const response = await axios.get(`/api/search?q=${query}`)
        this.searchResults = response.data
      } catch (error) {
        console.error('搜索失败:', error)
      }
    }
  }
}
</script>

使用自定义指令实现防抖

可以创建自定义指令来封装防抖逻辑,使模板更简洁。

// 注册全局防抖指令
Vue.directive('debounce', {
  inserted(el, binding) {
    let timer
    el.addEventListener('input', () => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        binding.value()
      }, 500)
    })
  }
})

// 组件中使用
<template>
  <input v-model="searchQuery" v-debounce="search" placeholder="搜索...">
</template>

<script>
export default {
  data() {
    return {
      searchQuery: ''
    }
  },
  methods: {
    search() {
      console.log('执行搜索:', this.searchQuery)
    }
  }
}
</script>

使用第三方库如lodash的防抖函数

对于更复杂的防抖需求,可以使用lodash的防抖函数。

import { debounce } from 'lodash'

export default {
  data() {
    return {
      searchQuery: ''
    }
  },
  created() {
    this.debouncedSearch = debounce(this.performSearch, 500)
  },
  watch: {
    searchQuery(newVal) {
      this.debouncedSearch(newVal)
    }
  },
  methods: {
    performSearch(query) {
      console.log('执行搜索:', query)
    }
  }
}

显示搜索建议

实现搜索建议功能可以在用户输入时显示匹配的结果列表。

<template>
  <div>
    <input v-model="searchQuery" @input="showSuggestions" placeholder="搜索...">
    <ul v-if="suggestions.length">
      <li v-for="(item, index) in suggestions" :key="index" @click="selectSuggestion(item)">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      suggestions: [],
      allItems: ['苹果', '香蕉', '橙子', '西瓜', '葡萄'] // 示例数据
    }
  },
  methods: {
    showSuggestions() {
      if (this.searchQuery.length > 0) {
        this.suggestions = this.allItems.filter(item =>
          item.includes(this.searchQuery)
        )
      } else {
        this.suggestions = []
      }
    },
    selectSuggestion(item) {
      this.searchQuery = item
      this.suggestions = []
      this.performSearch(item)
    }
  }
}
</script>

以上方法可以根据具体需求选择或组合使用,核心思想是通过监听输入变化并配合防抖机制来优化性能。

vue实现搜索自动查询

标签: vue
分享给朋友:

相关文章

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组件…

vue 实现直播

vue 实现直播

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

vue实现bootstrap

vue实现bootstrap

Vue 中集成 Bootstrap 的方法 在 Vue 项目中集成 Bootstrap 可以通过以下方式实现,涵盖样式、组件和交互功能。 安装 Bootstrap 依赖 通过 npm 或 yarn…

vue实现单据

vue实现单据

Vue 实现单据功能的方法 使用 Vue 实现单据功能通常涉及表单设计、数据绑定、验证和提交等环节。以下是具体实现方案: 表单设计与数据绑定 使用 Vue 的 v-model 指令实现表单数据的双…

vue observer实现

vue observer实现

Vue Observer 实现原理 Vue 的响应式系统核心是通过 Object.defineProperty(Vue 2)或 Proxy(Vue 3)实现的 Observer 模式。以下是关键实现细…

vue实现123456

vue实现123456

Vue 实现数字 123456 的显示 在 Vue 中显示数字 123456 非常简单,可以通过以下方法实现: 方法一:直接在模板中显示 <template> <div>…