Utilize Vue.js to selectively display or manipulate objects with a

I am currently working on a Vue.js component page that receives data from my backend. The page consists of three different filters/states that users can choose from: Unlabeled, Completed, and Skipped.

  • Unlablled
  • Completed
  • Skipped

My approach involves using collect.js to simplify manipulation of the object containing the records:

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());

Users can interact with the page by clicking on the filter they prefer:

<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>

Although the code functions as expected, I feel that it is rather cumbersome and lacks scalability. I'm open to suggestions on how to improve this process for future enhancements or additional filtering options.

Answer №1

Understanding the specific format of your data and potential future filter requirements is essential in providing a tailored solution. One effective approach could be implementing a filter class/object to define filtering criteria, such as:

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

You can now retrieve filtered data using 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;
}

The user interface can be structured as follows:

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

This scalable approach allows for seamless integration of additional filters by simply adding them to the filters array. By following this method, you can easily manage multiple filters without altering the existing code base. This solution is tailored based on the provided information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to open new window on iOS devices using $window.open

alertPopup.then (function(res) { if(ionic.Platform.isAndroid()) { $window.open('android_link_here', '_system') } else if(ionic.Platform.isIOS()) { $window.open('ios_link_here', '_system& ...

The POST request made using Postman shows an empty Node.js/Express req.body

Here is the current code snippet I am working with: var express = require('express'); var router = express.Router(); var db = require('../helpers/db'); var data = { "1": 127, "2": 236, "3": 348 } router.get('/', ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

I am experiencing challenges with utilizing moment and angular filters

I was able to get this code working perfectly before the recent jsfiddle update. However, now it seems to be causing issues. Any assistance would be greatly appreciated. Let's start with the HTML code: <div ng-app="app" ng-controller="ctrl"> ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

Am I going too deep with nesting in JavaScript's Async/Await?

In the process of building my React App (although the specific technology is not crucial to this discussion), I have encountered a situation involving three asynchronous functions, which I will refer to as func1, func2, and func3. Here is a general outline ...

Prevent animations on child elements with Vue.js

I am dealing with a scenario where I want to remove the fade transition on a child div within a <transition> component. The reason for nesting it is to prevent layout flickering, which can be demonstrated in a fiddle if necessary. In the fiddle belo ...

Ways to incorporate conditional logic with URL query parameters in Next.JS

I'm trying to implement conditional logic based on a URL query. In this scenario, I want to greet Kátia Fantes dynamically when she visits localhost:3000/katia-fantes. Any suggestions on how to achieve this? import { useRouter } from 'next/rou ...

Encountering issues while attempting to utilize pdf2json in a TypeScript environment

When attempting to import pdf2json (3.0.1) into my Node project using TypeScript, I encountered the following error: "Could not find a declaration file for module 'pdf2json'." I also tried installing @types/pdf2json for TypeScript but found tha ...

What could be the reason my this.setState is not properly updating the array?

Is there something I'm overlooking? I've implemented the es6 style to add to an empty array in this.state, but nothing is being pushed to state. I should have a total of two elements inside the array, however, after console.logging, nothing is a ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

Utilizing Multiple Canvases Simultaneously

I'm facing an issue where I need to crop multiple images on a single page using the canvas tag in HTML5 along with JavaScript. However, only one image is displaying on the page. How can I resolve this? The code snippet that I have attempted is provid ...

The encoding error in the encoding process must adhere to valid encoding standards

I recently developed a basic program that utilizes process.stdin and process.stdout. However, when I executed the program and tried to input a value for stdout, an error message popped up stating "TypeError: 'encoding' must be a valid string enco ...

What is the best way to extract all the data from a JSON using a shared key?

I'm trying to extract an array containing all the name values from a JSON structure. This is how my JSON data is structured: { "profile": { "G5j7": { "name": "siddharth", "age": &quo ...

Steps for designing an HTML table that expands and collapses partially

I am currently revamping an old "Top Screens" page by expanding the display from the top 30 to the top 100 in a basic html table format. However, I only want to show the top 20 on page load with an expand/collapse feature. While I have come across examples ...

How can I identify when a CSS transition on a particular element has ended if there are several transitions occurring simultaneously?

In my coding, I have been utilizing the following method to identify when a CSS3 transition has finished: CACHE.previewControlWrap.css({ 'bottom':'-217px' }).one('webkitTransitionEnd transitionend m ...

Is there a way to print an HTML page in Landscape mode within my Vue.js project?

I have been able to successfully print an HTML page in Landscape mode using the code below. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,maximum-scale=1.0"> ...

Exploring the possibilities of utilizing JavaScript within TypeScript

My dynamic javascript object holds all the resources (translation strings) for my app. Here's how it is structured: var ResourceManager = (function () { function ResourceManager() { var currentLanguage = $('#activeLanguage').htm ...

What is the process for including a task in the current method?

I've been working on building a web app similar to Google Calendar. I have successfully created the necessary objects and methods, but now I need to implement a feature that allows users to add tasks. My current idea is for users to input a task which ...

Challenge arises when implementing conditional styling in Vuejs

I want to include a style that works in HTML: <div style="text-decoration: line-through"> Now I am attempting this in Vue.js 2: <div :style="{'text-decoration: line-through':true}"> However, the above code is not functioning corre ...