当前位置:首页 > 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 Router实现。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。 基本路由配置 安装Vue Router…

vue实现多个tab

vue实现多个tab

Vue 实现多个 Tab 的方法 使用动态组件切换 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现多个…

vue实现简单的弹窗

vue实现简单的弹窗

使用 Vue 实现简单弹窗 组件基础结构 创建一个名为 Modal.vue 的组件文件,包含模板、脚本和样式部分: <template> <div class="mod…

vue播放倍速怎么实现

vue播放倍速怎么实现

实现Vue播放倍速的方法 在Vue中实现播放倍速功能通常涉及HTML5的<video>元素或第三方播放器库。以下是几种常见实现方式: 使用原生HTML5 video元素 通过ref获取…

vue路由实现内部切换

vue路由实现内部切换

Vue 路由实现内部切换的方法 Vue Router 是 Vue.js 官方的路由管理器,用于实现单页应用(SPA)的页面切换。以下是几种常见的内部路由切换方式: 使用 <router-li…

vue实现双折线图

vue实现双折线图

实现双折线图的步骤 安装必要的依赖库(如 ECharts 或 Chart.js),这里以 ECharts 为例: npm install echarts --save 在 Vue 组件中引入 EC…