Displaying all API data by default in Vue.js, even with filters, sorting, and search enabled - how can it be done?

I am currently utilizing Vue.js version 3 and below is the code snippet:

<template>
  <h5>List of Products</h5>

        <h3>Filter</h3> 
        <button v-on:click="resetOptions">Reset</button>
        <button v-on:click="sorting">Sorting</button>
        <button v-on:click="sorting2">Sorting2</button>
        <select v-model="category">
            <option value="Accessories">Accessories</option>
            <option value="Laptop">Laptop</option>
            <option value="Stationary">Stationary</option>
        </select> 
        <div>
        <input type="checkbox" name="test" id="test" v-model="city"  value='Roma'  /> 
        <label for="test"> Roma</label>
        <input type="checkbox" name="test2" id="test2" v-model.trim="city" value='Barselona'  />
        <label for="test2"> Barselona</label>
        <input type="checkbox" name="test3" id="test3" v-model.trim="city" value='Milano'  />
        <label for="test3"> Milano</label>
        </div> 
        
        <input type="text" v-model="name" placeholder="Filter By Name"/>

        <label for="vol">Price (between 0 and 1000):</label>
    
        <input type="range" v-model.trim="range" min="0" max="1000" step="10"/>  
        <ul>
            <li v-for="product in filterProducts" :key="product.price"> Product Name : {{product.name}} - Price : {{product.price}} ({{product.category}}) 
                {{product.city}}
            </li>
        </ul>
</template>

<script>
window.axios = require("axios");

export default {
 data: ()=> ({
            city:['Barselona', 'Milano' , 'Roma'],
            category: '',
            name: '',
            range: '10000',
            products: [] ,
        }),
        
         mounted(){
             axios.get('http://localhost:3000/products')
             .then(response =>this.products = response.data);
         },

              computed: {
            filterProducts: function(){
return this.filterProductsByName(this.filterProductsByRange(this.filterProductsByCity(this.filterProductsByCategory(this.products))))
},

        },
        
        methods: {

filterProductsByCategory: function(products){
return products.filter(product => !product.category.indexOf(this.category))
},

            filterProductsByName: function(products) {
return products.filter(product => !product.name.toLowerCase().indexOf(this.name.toLowerCase()))
},

            filterProductsByCity: function(products) {
return products.filter(product => this.city.indexOf(product.city) !== -1)
},

 filterProductsByRange: function(products){
return products.filter(product => (product.price >= 0 && product.price <= this.range) ? product : '')
},

            sorting:function(){
this.products.sort((a,b)=>(a.price > b.price) ? 1 : -1)
},
             sorting2:function(){
this.products.sort((a,b)=>(a.price < b.price) ? 1 : -1)
},

            uniqueCheck(e){
this.city = [];
if (e.target.checked) {
                 this.city.push(e.target.value);
               }
         },

            resetOptions:function(){
this.category='',
this.city='',
this.name='',
this.range='1000'
},
        },

}
</script>

<style>

</style>

Currently, my API data is displayed by default due to pre-filled values in the city array. However, I would like my checkboxes to be unchecked by default and display all data initially. Upon checking a checkbox, I want to filter my data accordingly. How can I achieve this?

For reference, here is an image of fake JSON data: https://i.sstatic.net/otNbh.jpg

Answer №1

Revamp all your filter functions to default back to the original products array when no specific filter is set:

export default {
  methods: {
    filterProductsByCategory: function (products) {
      return this.category
        ? products.filter((product) => !product.category.indexOf(this.category))
        : products
    },

    filterProductsByName: function (products) {
      return this.name
        ? products.filter(
            (product) =>
              !product.name.toLowerCase().indexOf(this.name.toLowerCase())
          )
        : products
    },

    filterProductsByCity: function (products) {
      return this.city && this.city.length
        ? products.filter((product) => this.city.indexOf(product.city) !== -1)
        : products
    },

    filterProductsByCity2: function (products) {
      return this.city && this.city.length
        ? products.filter((product) => !product.city.indexOf(this.city))
        : products
    },

    filterProductsByRange: function (products) {
      return this.range
        ? products.filter((product) =>
            product.price >= 0 && product.price <= this.range ? product : ""
          )
        : products
    },
  }
}

demo

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

In my experience, the GET request is functioning properly within Postman, but for some reason the POST method continues to send requests repeatedly

ISSUE: I am encountering a problem while making a POST request in Postman. The application keeps sending requests without receiving any response. I have read through various solutions for Postman hanging during a POST request, but none of them seem to sol ...

Obtain the HTML source code for a webpage that has been scrolled down using Python web scraping with Selenium

Even after executing a script to scroll down, I am only able to retrieve the initial html code containing 11 hotels. How can I access the entire data source code by scrolling down to scrape all the available hotels? If the driver.execute_script is suppose ...

"Encountering a Prisma type error while attempting to add a new record

I am currently utilizing Prisma with a MySQL database. Whenever I attempt to create a new record (School), an error of type pops up in the console. Additionally, I am implementing a framework called Remix.run, although it does not seem to be causing the is ...

How can I display an HTML document by uploading it and rendering it in VueJs?

I am looking for a way to display HTML documents on the front end of my Vue.js application. My goal is to retrieve the HTML content from my database and render it seamlessly on the user interface. Any suggestions or guidance would be greatly appreciated. ...

Organize and categorize items

I need help sorting an object displayed below. My goal is to calculate the sum of all rating properties for each object, and then sort the objects based on the highest total rating. For instance, if the total rating for Intro 1 is 7 and for Intro 2 is 3, ...

Tips for incorporating filtering and sorting functionality in a API-focused application using React and Next.js

In my current project, I am developing a React application using Next.js. The main goal is to fetch data from an API and display cards based on user-selected filters. Specifically, I aim to retrieve the cards initially and then filter them according to the ...

What is the process for extracting Excel .xlsx information from a POST request body in an Express API?

I've created an Angular frontend application that sends an excel (.xlsx) file as form data in the request body to my Express endpoint. Take a look at the function from my Angular service file below: uploadOrder(workOrder: File) { const formData: For ...

Encountering issues with proper function of history.listen within React Router

I am struggling to get my function to work every time React detects a change in the URL. The history.listen method is not triggering (the console.log statement is not showing up). I have read that this issue may be related to using BrowserRouter, but when ...

Best practices for incorporating packages in Vue.JS SPA applications

Currently, in my vue-cli/webpack project, I have been incorporating new packages using the command: yarn add <package> --dev These packages are stored in the package.json file under devDependencies. While the setup works smoothly, the build process ...

If the ID (i.e. document.getElementById) is not found, then keep JavaScript running

I'm currently working on a JavaScript project where I need the script to gracefully handle missing div-ids and continue executing. I've looked into various solutions, but many involve either replacing the missing ID or placing information into an ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. https://i.sstatic.net/ogFA3.png The content provided was considered valid. https://i.sstatic.net/ar5FJ.png An error ...

Playing with vue component dependencies

During my attempt to run a unit test, I encountered an error when making an axios call. To handle this error, I successfully mocked the call but faced an issue when trying to utilize an external library dependency (specifically, vue-toasted) to display an ...

Implement currency formatting in input text with v-model in Vue

Is there a way to add a currency sign to the input value in such a way that it appears as part of the input itself? For example, how can I make it display "10 $" when the user inputs 10 while still keeping "10" as the actual data value of amount? input( ...

What are the steps to implement server side routing using react-router 2 and expressjs?

If you're looking to delve into server side rendering with react-router, the documentation linked here might fall short in providing a comprehensive understanding. In particular, it may not offer enough insights on how to leverage react-router 2 for r ...

Creating dynamic styles with Material-UI's useStyles

Attempting to implement the same logic using material-ui's useStyle feature <div className={'container ' + (state.unlocked ? 'containerUnlocked' : '')}> I thought it might look like this: <div className={`${clas ...

Utilizing Translation (i18n) in AngularJS Controller to Implement Popups

I'm currently working on an AngularJS app and need to implement i18n. Everything is running smoothly except for error handling, specifically with utilizing translations in controller for popups. Here is a snippet of my controller: function showError ...

Using Vue.js, perform calculations on various fields within an array of objects generated by the v-for directive

I am currently learning Vue.js and I have implemented a v-for loop to iterate through an array of objects. However, I now need to calculate a specific field (precoPorKg) within this loop. In order to perform this calculation, the input item.quantidade mus ...

The distance calculation is not functioning properly within the for loop

I am currently working on developing a geolocation test app. After finding some useful code for calculating the distance between two points using latitude and longitude coordinates, I am attempting to create a loop using a for loop to calculate the distan ...

NodeJS buffer is not capable of handling incomplete TCP stream data

While troubleshooting my TCP JSON stream on the live server, I discovered that if the data streamed to me in JSON format is excessive, it doesn't consistently parse correctly. It requires multiple streams for successful parsing. Here is the code I am ...

Issue with exporting Typescript React component

Despite searching for answers, none of the related questions have been helpful... My goal is to export React components from a TypeScript library that I plan to publish on npm. For testing purposes before publishing, I am utilizing npm link. The structu ...