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?
>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,
};
},
};