当前位置:首页 > VUE

vue 实现搜索联想

2026-03-09 09:05:14VUE

Vue 实现搜索联想功能

搜索联想(Search Suggestions)是一种常见的用户体验优化功能,可以在用户输入时实时显示相关的搜索建议。以下是使用 Vue 实现搜索联想的几种方法。

使用 Vue 的 v-model 和 computed 属性

通过 Vue 的 v-model 绑定输入框的值,结合 computed 属性或 watch 监听输入变化,动态过滤匹配的联想词。

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

<script>
export default {
  data() {
    return {
      searchQuery: '',
      allSuggestions: ['苹果', '香蕉', '橙子', '西瓜', '葡萄']
    };
  },
  computed: {
    suggestions() {
      if (!this.searchQuery) return [];
      return this.allSuggestions.filter(item =>
        item.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    }
  },
  methods: {
    selectSuggestion(item) {
      this.searchQuery = item;
    }
  }
};
</script>

使用防抖优化性能

频繁触发搜索联想可能会导致性能问题,可以通过防抖(Debounce)技术减少请求次数。

<template>
  <div>
    <input v-model="searchQuery" placeholder="输入搜索内容" />
    <ul v-if="suggestions.length">
      <li v-for="item in suggestions" :key="item">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
import { debounce } from 'lodash';

export default {
  data() {
    return {
      searchQuery: '',
      suggestions: [],
      allSuggestions: ['苹果', '香蕉', '橙子', '西瓜', '葡萄']
    };
  },
  watch: {
    searchQuery: debounce(function(newVal) {
      if (!newVal) {
        this.suggestions = [];
        return;
      }
      this.suggestions = this.allSuggestions.filter(item =>
        item.toLowerCase().includes(newVal.toLowerCase())
      );
    }, 300)
  }
};
</script>

结合后端 API 实现动态联想

如果需要从后端获取联想数据,可以通过 axios 或其他 HTTP 客户端发送请求。

<template>
  <div>
    <input v-model="searchQuery" placeholder="输入搜索内容" />
    <ul v-if="suggestions.length">
      <li v-for="item in suggestions" :key="item.id">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';
import { debounce } from 'lodash';

export default {
  data() {
    return {
      searchQuery: '',
      suggestions: []
    };
  },
  watch: {
    searchQuery: debounce(function(newVal) {
      if (!newVal) {
        this.suggestions = [];
        return;
      }
      this.fetchSuggestions(newVal);
    }, 300)
  },
  methods: {
    fetchSuggestions(query) {
      axios.get(`/api/suggestions?q=${query}`)
        .then(response => {
          this.suggestions = response.data;
        })
        .catch(error => {
          console.error('获取联想词失败:', error);
        });
    }
  }
};
</script>

使用第三方库实现更复杂功能

如果需要更高级的搜索联想功能(如高亮匹配部分、分组显示等),可以使用第三方库如 vue-suggestionautocomplete.js

<template>
  <div>
    <autocomplete
      :search="searchFunction"
      placeholder="输入搜索内容"
      @submit="handleSubmit"
    ></autocomplete>
  </div>
</template>

<script>
import Autocomplete from '@trevoreyre/autocomplete-vue';

export default {
  components: {
    Autocomplete
  },
  methods: {
    searchFunction(query) {
      return ['苹果', '香蕉', '橙子'].filter(item =>
        item.toLowerCase().includes(query.toLowerCase())
      );
    },
    handleSubmit(result) {
      console.log('选中:', result);
    }
  }
};
</script>

样式优化

为联想列表添加基础样式,提升用户体验。

vue 实现搜索联想

ul {
  list-style: none;
  padding: 0;
  margin: 0;
  border: 1px solid #eee;
  max-height: 200px;
  overflow-y: auto;
}

li {
  padding: 8px 12px;
  cursor: pointer;
}

li:hover {
  background-color: #f5f5f5;
}

以上方法可以根据实际需求选择或组合使用,实现高效的搜索联想功能。

标签: vue
分享给朋友:

相关文章

vue实现裁剪头像

vue实现裁剪头像

Vue 实现头像裁剪功能 实现头像裁剪功能通常需要结合第三方库如 cropperjs 或 vue-cropper。以下是两种常见实现方式: 使用 vue-cropper 库 安装依赖: n…

vue实现级联

vue实现级联

Vue 实现级联选择器的方法 级联选择器(Cascader)是常见的表单组件,用于处理多层级联动数据选择(如省市区选择)。以下是几种实现方式: 基于 Element UI 的 el-cascader…

vue实现jqueryui

vue实现jqueryui

Vue 实现 jQuery UI 功能 在 Vue 项目中实现类似 jQuery UI 的功能,可以通过原生 Vue 组件或第三方库来实现。以下是几种常见 jQuery UI 功能的 Vue 替代方案…

vue实现markdown

vue实现markdown

Vue 实现 Markdown 编辑器 在 Vue 中实现 Markdown 编辑器可以通过集成第三方库或自定义解析器完成。以下是两种常见方法: 使用第三方库(如 marked 或 markdown…

computed vue 实现

computed vue 实现

computed 在 Vue 中的基本用法 Vue 的 computed 属性用于声明依赖于其他数据的计算属性。当依赖的数据变化时,计算属性会自动重新计算并缓存结果。 export defaul…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…