当前位置:首页 > VUE

vue实现input动态搜索

2026-01-20 18:07:23VUE

Vue 实现动态搜索功能

使用 Vue 实现动态搜索功能通常涉及监听输入框变化、发送异步请求和展示结果。以下是几种常见实现方式:

使用 v-model 和 watch

<template>
  <div>
    <input v-model="searchQuery" placeholder="Search..." />
    <ul v-if="results.length">
      <li v-for="result in results" :key="result.id">
        {{ result.name }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      results: [],
      timeout: null
    }
  },
  watch: {
    searchQuery(newVal) {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.performSearch(newVal)
      }, 300)
    }
  },
  methods: {
    async performSearch(query) {
      if (query.length < 2) {
        this.results = []
        return
      }
      const response = await fetch(`/api/search?q=${query}`)
      this.results = await response.json()
    }
  }
}
</script>

使用计算属性

<template>
  <div>
    <input v-model="searchQuery" 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: [] // 从API获取或本地数据
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => 
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

使用自定义指令

<template>
  <div>
    <input v-model="searchQuery" v-debounce="onSearch" placeholder="Search..." />
    <ul v-if="results.length">
      <li v-for="result in results" :key="result.id">
        {{ result.name }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  directives: {
    debounce: {
      inserted(el, binding) {
        let timeout
        el.addEventListener('input', () => {
          clearTimeout(timeout)
          timeout = setTimeout(() => {
            binding.value(el.value)
          }, 300)
        })
      }
    }
  },
  data() {
    return {
      searchQuery: '',
      results: []
    }
  },
  methods: {
    async onSearch(query) {
      if (query.length < 2) {
        this.results = []
        return
      }
      const response = await fetch(`/api/search?q=${query}`)
      this.results = await response.json()
    }
  }
}
</script>

使用第三方库

对于更复杂的需求,可以考虑使用 lodash 的 debounce 或 vue-use 的组合式 API:

<template>
  <div>
    <input v-model="searchQuery" placeholder="Search..." />
    <ul v-if="results.length">
      <li v-for="result in results" :key="result.id">
        {{ result.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import { ref, watch } from 'vue'
import { useDebounceFn } from '@vueuse/core'

export default {
  setup() {
    const searchQuery = ref('')
    const results = ref([])

    const performSearch = useDebounceFn(async (query) => {
      if (query.length < 2) {
        results.value = []
        return
      }
      const response = await fetch(`/api/search?q=${query}`)
      results.value = await response.json()
    }, 300)

    watch(searchQuery, (newVal) => {
      performSearch(newVal)
    })

    return { searchQuery, results }
  }
}
</script>

性能优化建议

  1. 添加防抖(debounce)避免频繁请求
  2. 设置最小字符限制(如至少2个字符才搜索)
  3. 取消未完成的请求(使用AbortController)
  4. 添加加载状态和错误处理
  5. 考虑本地缓存结果

这些方法可以根据项目需求选择或组合使用,Vue 3的组合式API提供了更灵活的代码组织方式。

vue实现input动态搜索

标签: 动态vue
分享给朋友:

相关文章

vue实现自动翻译

vue实现自动翻译

Vue 实现自动翻译的方法 在 Vue 项目中实现自动翻译功能可以通过多种方式完成,以下是几种常见的方法: 使用第三方翻译 API 注册并获取翻译 API 的密钥(如 Google Transla…

vue实现sql操作

vue实现sql操作

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

vue实现好友列表

vue实现好友列表

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

vue实现绑卡的原理

vue实现绑卡的原理

Vue 实现绑卡的原理 Vue 实现绑卡功能通常涉及前端表单处理、数据绑定、验证以及和后端 API 的交互。以下是实现绑卡功能的核心原理和步骤: 数据绑定与表单处理 Vue 通过 v-model…

vue实现发表

vue实现发表

Vue 实现发表功能 在 Vue 中实现发表功能通常涉及表单处理、数据绑定和网络请求。以下是实现步骤和代码示例: 表单设计与数据绑定 创建一个表单用于输入发表内容,使用 v-model 进行数据双…

vue 指令实现

vue 指令实现

Vue 指令实现 Vue 指令是 Vue.js 提供的特殊属性,用于在 DOM 元素上添加特殊行为。指令以 v- 前缀开头,例如 v-model、v-if、v-for 等。以下是实现自定义指令和常用内…