当前位置:首页 > VUE

vue实现前端搜索

2026-01-17 09:14:58VUE

Vue 实现前端搜索功能

在 Vue 中实现前端搜索功能,通常需要结合数据绑定、计算属性和列表渲染等技术。以下是几种常见的实现方法:

基于计算属性的搜索

通过计算属性对数据进行过滤,实现搜索功能:

vue实现前端搜索

<template>
  <div>
    <input v-model="searchQuery" placeholder="Search...">
    <ul>
      <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' }
      ]
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(item => 
        item.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  }
}
</script>

使用 watch 实现搜索

对于需要异步操作或更复杂逻辑的搜索,可以使用 watch:

<script>
export default {
  data() {
    return {
      searchQuery: '',
      items: [],
      filteredItems: []
    }
  },
  watch: {
    searchQuery(newVal) {
      this.filteredItems = this.items.filter(item =>
        item.name.toLowerCase().includes(newVal.toLowerCase())
      )
    }
  },
  created() {
    // 假设这里是从API获取数据
    this.items = [
      { id: 1, name: 'Apple' },
      { id: 2, name: 'Banana' },
      { id: 3, name: 'Orange' }
    ]
    this.filteredItems = [...this.items]
  }
}
</script>

使用第三方库实现高级搜索

对于更复杂的搜索需求,可以考虑使用第三方库如 Fuse.js:

vue实现前端搜索

import Fuse from 'fuse.js'

export default {
  data() {
    return {
      searchQuery: '',
      items: [
        { id: 1, name: 'Apple', category: 'fruit' },
        { id: 2, name: 'Banana', category: 'fruit' },
        { id: 3, name: 'Carrot', category: 'vegetable' }
      ],
      fuse: null
    }
  },
  computed: {
    searchResults() {
      if (!this.searchQuery) return this.items
      return this.fuse.search(this.searchQuery).map(result => result.item)
    }
  },
  created() {
    const options = {
      keys: ['name', 'category'],
      threshold: 0.3
    }
    this.fuse = new Fuse(this.items, options)
  }
}

实现搜索高亮

为搜索结果中的匹配部分添加高亮效果:

<template>
  <div>
    <input v-model="searchQuery" placeholder="Search...">
    <ul>
      <li v-for="item in filteredItems" :key="item.id">
        <span v-html="highlightMatches(item.name)"></span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  methods: {
    highlightMatches(text) {
      if (!this.searchQuery) return text
      const regex = new RegExp(this.searchQuery, 'gi')
      return text.replace(regex, match => `<span class="highlight">${match}</span>`)
    }
  }
}
</script>

<style>
.highlight {
  background-color: yellow;
  font-weight: bold;
}
</style>

结合 Vuex 实现全局搜索

在大型应用中,可以使用 Vuex 管理搜索状态:

// store.js
export default new Vuex.Store({
  state: {
    searchQuery: '',
    items: []
  },
  mutations: {
    setSearchQuery(state, query) {
      state.searchQuery = query
    }
  },
  getters: {
    filteredItems: state => {
      return state.items.filter(item =>
        item.name.toLowerCase().includes(state.searchQuery.toLowerCase())
      )
    }
  }
})

// 组件中使用
<template>
  <div>
    <input 
      :value="searchQuery" 
      @input="updateSearchQuery($event.target.value)"
      placeholder="Search..."
    >
    <ul>
      <li v-for="item in filteredItems" :key="item.id">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations } from 'vuex'

export default {
  computed: {
    ...mapState(['searchQuery']),
    ...mapGetters(['filteredItems'])
  },
  methods: {
    ...mapMutations(['setSearchQuery']),
    updateSearchQuery(query) {
      this.setSearchQuery(query)
    }
  }
}
</script>

以上方法可以根据具体需求选择使用,从简单的本地搜索到复杂的全局搜索都能满足。对于大型数据集,建议考虑后端搜索或使用 Web Worker 来避免阻塞主线程。

标签: vue
分享给朋友:

相关文章

vue实现跑车

vue实现跑车

Vue 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

ssh vue 实现

ssh vue 实现

使用SSH连接Vue项目部署的服务器 在Vue项目开发或部署过程中,可能需要通过SSH连接到远程服务器进行配置或维护。以下是实现SSH连接并部署Vue项目的关键步骤: 生成SSH密钥对 在本地终端运…

vue实现input

vue实现input

Vue 实现 Input 输入框的方法 基本双向绑定 使用 v-model 指令实现双向数据绑定,适用于大多数表单场景: <template> <input v-model="…

vue 实现modal

vue 实现modal

Vue 实现 Modal 的方法 使用 Vue 原生组件 通过 Vue 的组件系统可以轻松实现 Modal。创建一个可复用的 Modal 组件,通过 props 控制显示与隐藏。 <templ…

vue实现curd

vue实现curd

Vue实现CRUD操作 初始化Vue项目 使用Vue CLI创建新项目,安装必要依赖如axios用于HTTP请求 vue create crud-demo cd crud-demo npm inst…

vue实现导航

vue实现导航

使用 Vue Router 实现导航 Vue Router 是 Vue.js 官方提供的路由管理器,用于构建单页应用(SPA)的导航系统。以下是实现导航的基本步骤。 安装 Vue Router n…