Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
Filter object with Vue.js

I have a Vue.js component page that gets some data from my backend:

<script setup>
const props = defineProps({
    records: {
        type: Object,
    },
});
</script>

I have three different filters/states which I want my users to be able to select from:

  • Unlablled
  • Completed
  • Skipped

Below is how I get the records for the different filters. I am using collect.js to make working with the object easier:

let getRecords = () => {
    return collect(props.records)
}


const getUnlabeledRecords = () => {
    return getRecords()
        .where('skipped', false)
        .where('processed', false);
}
const getCompletedRecords = () => {
    return getRecords()
        .where('processed', true);
}

const getSkippedRecords = () => {
    return getRecords()
        .where('processed', false)
        .where('skipped', true);
}

//Load all records on page load.
const allRecords = ref(getUnlabeledRecords());

//Show current record to the user.
const current = ref(allRecords.value.first());

My users can then click on the filter they want:

<a :class="{'bg-gray-100' : currentFilter === 'Unlabeled' }"
   @click="allRecords = getUnlabeledRecords(), currentFilter = 'Unlabeled'">
    Unlabeled ({{ getUnlabeledRecords().count() }})
</a>
<a :class="{'bg-gray-100' : currentFilter === 'Skipped' }"
   @click="allRecords = getSkippedRecords(), currentFilter = 'Skipped'">
    Skipped ({{ getSkippedRecords().count() }})
</a>
<a :class="{'bg-gray-100' : currentFilter === 'Completed' }"
   @click="allRecords = getCompletedRecords(), currentFilter = 'Completed'">
    Completed ({{ getCompletedRecords().count() }})
</a>

The above code works, but it feels very "clunky", and not very scaleable. Say, I want to introduce more advanced filtering - or just other "filter options", I have to duplicate a lot of code.

Anyone have suggestions on how I can do this in a better way?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's a bit of a broad question because we don't know the format of your data or what potential future filters you may want. This makes it hard to give you an actual good answer. However, an easy win would seem to be to introduce a filter class/object that holds the details of what you want to filter, like for example:

const filters = [
  {
    text: 'Unlabeled',
    statesToFilterOn: [
      { key: 'skipped', value: false },
      { key: 'processed', value: false },
    ]
  },
  {
    text: 'Skipped',
    statesToFilterOn: [
      { key: 'skipped', value: true },
      { key: 'processed', value: false },
    ]
  }
]

Now you can get filtered data with a getFilteredData method:

const currentFilteredData = ref(getRecords());
const currentFilter = ref();

function applyFilter(filter) {
  currentFilter.value = filter;
  currentFilteredData.value = getFilteredData(filter);
}

function getFilteredData(filter) {
  let filtered = getRecords();

  filter.statesToFilterOn.forEach(state => {
    filtered = filtered.where(state.key, state.value);
  });

  return filtered;
}

And your UI can look like this:

<a 
  v-for="filter in filters" 
  :key="filter.text"
  @click="applyFilter(filter)"
>
  {{ filter.text }} ({{ getFilteredData(filter).count }})
</a>

And now if you want to add more filters, just add one to the filters array. You can do this as many times as you want and you don't have to change anything but the filters array. I think this is as good of an answer as I can give with the information given.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda