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

Navigating through Index in #each in emberjs

Take a look at the code provided below: http://jsbin.com/atuBaXE/2/ I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature: {{#each item in model}} {{@index} ...

Establishing the null values for input parameters

Whenever the button is clicked, I want to reset the input values to null. The function spremi() gets triggered when the button is clicked, but I want to set the values of podaci.tezina and podaci.mamac back to their initial values so that the user can en ...

Utilize and store images based on the individual user's preferences with PlayCanvas

Currently, I am immersed in a PlayCanvas endeavor where I am trying to render specific objects with textures of my choice. The main issue arises when I come across the config.json file in the PlayCanvas build. Within this file, there is a designated path ...

AngularJS making use of multiple checkboxes to filter data from a nested JSON structure

Hi everyone, I came across a helpful resource on implementing multiple checkboxes filters in AngularJS: angular js multiple checkbox with custom filters I am facing a similar issue but with a multilevel JSON structure. Here is an example of what I am deal ...

Obtain JavaScript object from WebView in Swift

Currently, I am displaying a webView in my iOS app using Swift. My goal is to retrieve an object from the JavaScript code within the webView. Upon inspecting the console, I discovered that the desired object is named "window.user". However, when attempti ...

Tips for setting up a range slider for decimal numbers

I have implemented the following code for a range slider. It works perfectly fine for integer values like 1 and 100, but I am facing issues when trying to use decimal values. I attempted to substitute 1 with 0.1 but it did not yield the desired result. ...

Can you provide instructions on utilizing the async .update() function for DataTables within MDBootstrap?

I am just starting to explore MDBootstrap and I'm currently focused on grasping how to utilize the DataTables. While I've browsed through the examples on their website regarding Async table updates, I've found it a bit challenging to adapt i ...

Error: The initial parameter must be a string, Buffer, ArrayBuffer, Array, or Array-like Object. An object type was passed in instead in CryptoJS

In my quest to encrypt and decrypt data in react-native, I embarked on using the crypto node module by incorporating it into my react native project through browserify. While attempting encryption with the code snippet provided below, an error surfaces sta ...

Issue with swal() not triggering in Internet Explorer 11

Looking for some assistance here, I believe I might be missing a small detail. The _layout.cshtml file includes all the necessary scripts to ensure that sweetheart works on IE: (this used to work in previous versions, but we haven't had to support I ...

The Precision of the IRR (Internal Rate of Return) Calculation in Javascript

I've been working on a custom IRR function in JavaScript to mimic the functionality of Excel's IRR function. Despite my best efforts, it seems that my results are slightly off. Below is the code snippet that I have been using: var IRRval = []; ...

Categorize messages based on the date they were last read in Angular

I am looking to organize my chat application messages by date, similar to the layout in Microsoft Teams app. Here is an example of the message data: [ { "id": 577, "source": { "userID": 56469, ...

text box with an immobile header

As the browser window size decreases, the layout changes. However, when scrolling down, the search text box moves up and is no longer visible due to its lack of fixation. How can I make the search text box stay fixed as I scroll down? I tried implementing ...

Recursive routing in NodeJS using Express

Certain website APIs have the capability to perform actions such as: Initial user's id their first friend, also a user v v GET /api/users/54282/friends/0/friends/0 ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

Customize Cell Styling with Bootstrap Full Calendar CSS

I am attempting to implement a Bootstrap calendar feature where cells are colored green if the timestamp is greater than today's date. This can be achieved by: $checkTime > $today cell.css = green background I came across this code snippet on St ...

Vue.js <v-data-table> - Automatic sorting/ custom sorting options

I am trying to arrange the numerical data in a Vue.js data-table in descending order right from the start. I want it to look like the screenshot provided below. Screenshot of My Desired Result The data that needs to be arranged in descending order is the ...

Removing a row from a table seamlessly without the need to reload the page

I am having an issue with my page that displays a list of orders. When a user clicks on a button to delete a row from the table, it only removes the first row successfully. However, when attempting to delete the second or third row, it does not work. Can s ...

Is there a simpler way to retrieve data from PHP or to efficiently filter the data once it's been retrieved?

Creating a business directory website involves fetching data from a database. The issue arose when attempting to apply a function uniformly to all boxes, as only the first one with the specified id would function correctly. To address this problem, the fol ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...

What is the best way to compare two times in the hh:mm AM/PM format?

I need to handle times in the format of hh:mm AM/PM generated by a specific plugin, and perform comparisons on them using jQuery/javascript. When a user manually inputs a time, I require the text in the textbox to automatically adjust to hh:mm AM/PM with ...