Vue + TS封装全局搜索组件

本文介绍了如何使用Vue和TypeScript封装一个全局搜索组件。该组件可以方便地在Vue项目中使用,帮助用户快速定位所需信息。

组件功能

该全局搜索组件具有以下功能:

  • 可以搜索指定数据源中的数据
  • 支持模糊搜索和精确搜索
  • 可以自定义搜索结果的展示方式
  • 支持多种搜索数据源的切换

组件实现

该组件基于Vue和TypeScript开发。首先,需要在Vue项目中安装依赖:

npm install vue-class-component vue-property-decorator --save

然后,在Vue单文件组件中定义全局搜索组件:

<template>
  <div class="search-container">
    <input v-model="keyword" @input="search" />
    <div v-for="result in results" :key="result.id" @click="select(result)">
      <slot :result="result">{
    
    {
    
     result }}</slot>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import {
    
     Component, Prop, Watch } from 'vue-property-decorator';

@Component
export default class SearchComponent extends Vue {
    
    
  @Prop() data!: any[];
  @Prop({
    
     default: 'id' }) keyProp!: string;
  @Prop({
    
     default: 'name' }) labelProp!: string;
  @Prop({
    
     default: 'name' }) searchProp!: string;
  @Prop({
    
     default: true }) fuzzy!: boolean;

  keyword = '';
  results: any[] = [];

  search() {
    
    
    this.results = this.data.filter((item: any) => {
    
    
      const keyword = this.keyword.toLowerCase();
      const label = item[this.labelProp].toLowerCase();
      const searchValue = item[this.searchProp].toLowerCase();

      if (this.fuzzy) {
    
    
        return label.includes(keyword) || searchValue.includes(keyword);
      } else {
    
    
        return label === keyword || searchValue === keyword;
      }
    });
  }

  select(result: any) {
    
    
    this.keyword = result[this.labelProp];
    this.results = [];
    this.$emit('select', result);
  }
}
</script>

在上述代码中,我们定义了一个名为SearchComponent的Vue组件,该组件包含以下属性:

  • data:指定需要搜索的数据源
  • keyProp:指定数据源中每个数据项的唯一标识符属性名,默认为id
  • labelProp:指定数据源中每个数据项的展示名称属性名,默认为name
  • searchProp:指定数据源中每个数据项的搜索属性名,默认为name
  • fuzzy:指定是否使用模糊搜索方式,默认为true

在组件的模板中,我们使用input元素绑定了keyword属性,当用户输入关键字时触发search方法进行搜索,同时在div标签中使用v-for指令循环展示搜索结果,使用slot元素展示搜索结果的自定义展示方式。

组件使用

要使用全局搜索组件,可以在Vue单文件组件中引用该组件,然后通过data属性指定需要搜索的数据源,如:

<template>
  <div>
    <search-component :data="users" />
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import SearchComponent from './SearchComponent.vue';

export default Vue.extend({
    
    
  components: {
    
    
    SearchComponent,
  },
  data() {
    
    
    return {
    
    
      users: [
        {
    
     id: 1, name: 'Tom', email: '[email protected]' },
        {
    
     id: 2, name: 'Jerry', email: '[email protected]' },
        {
    
     id: 3, name: 'Alice', email: '[email protected]' },
        {
    
     id: 4, name: 'Bob', email: '[email protected]' },
      ],
    };
  },
});
</script>

在上述代码中,我们在Vue单文件组件中引用了SearchComponent组件,并通过data属性指定了需要搜索的数据源users

总结

本文介绍了如何使用Vue和TypeScript封装一个全局搜索组件。该组件可以方便地在Vue项目中使用,帮助用户快速定位所需信息。希望本文能够对Vue开发者有所帮助。

猜你喜欢

转载自blog.csdn.net/qq_27244301/article/details/131474680