Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I write a composable for filtering items for different data sources

i am a newbie to using vuejs and the compositions API . I would like to create a search filter that I can use for different data sources. is this possible with a composable?

what I have now in my component itself is:

const inputData = reactive({
    searchQuery: searchQuery,
});

const resultQuery = computed(() => {
    if (inputData.searchQuery) {
        return airports.filter((item) => {
            return inputData.searchQuery
                .toLowerCase()
                .split(' ')
                .every((v) => item.name.toLowerCase().includes(v));
        });
    } else {
        return datasource;
    }
});

I would like ‘airports’ to be different. in addition, it is of course difficult to know whether .name is available in that data source. Is it even a logical choice to make it a composable?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is an example of how you could create a search filter composable based on your needs :

import { ref, computed } from 'vue';

export function useSearchFilter(dataSource, searchQuery) {
  const searchTerm = ref(searchQuery);

  const filteredData = computed(() => {
    if (searchTerm.value) {
      return dataSource.filter((item) => {
        return searchTerm.value
          .toLowerCase()
          .split(' ')
          .every((v) => item.name.toLowerCase().includes(v));
      });
    } else {
      return dataSource;
    }
  });

  return {
    searchTerm,
    filteredData,
  };
}

You can then use this composable in a component by importing it and calling it in the component’s setup function. Here is an example of how you could use the composable in a component:

import { useSearchFilter } from './useSearchFilter';

export default {
  setup() {
    const dataSource = ref(airports);
    const { searchTerm, filteredData } = useSearchFilter(dataSource, '');

    return {
      searchTerm,
      filteredData,
    };
  },
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading