Sort through data based on specific data fields upon the button click event using JSON and Vue.js

Is there a way to use JSON files in Vue.js to filter data based on category when a button is pressed? I have objects with categories inside the data.

portfolio-v1.json

    {
  "data":[
    {
      "image_path":"static/products/DELUXE-BATHROBE.jpg",
      "title":"Beautiful Designs",
      "heading":"Lorem Ipsum is simply dummy.",
      "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
      "vendor":"George Courey",
      "category":"Blanket"
    },
    {
      "image_path":"static/products/HOME-CARE-SLIP-PAD.png",
      "title":"Mutifunctionals Blocks",
      "heading":"Lorem Ipsum is simply dummy.",
      "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
      "vendor": "George Courey",
      "category": "Blanket"
    },
    {
      "image_path":"static/products/HERRINGBONE-THERMAL-BLANKET.jpg",
      "title":"Vuejs App For Game",
      "heading":"Lorem Ipsum is simply dummy.",
      "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
      "vendor": "George Courey",
      "category": "Blanket"
    }
  ]
}

portfolioGrid.vue

<template>
  <div class="row col-space">
    <!-- START PORTFOLIO FILTER AREA -->
    <div class="col-12">
      <div class="text-center">
        <div class="portfolio-filter mb-40">
          <button class="active" data-filter="*">Show all</button>
          <button data-filter=".cat1">Linens</button>
          <button data-filter=".cat2">Blankets</button>
          <button data-filter=".cat3">Protective Products</button>
          <button data-filter=".cat4">Top Sheets</button>
          <button data-filter=".cat5">Staff Apparel</button>
          <button data-filter=".cat6">Towels</button>
          <button data-filter=".cat7">Bathrobes & Slippers</button>
        </div>
      </div>
    </div>
    <!-- END PORTFOLIO FILTER AREA -->
    <div v-for="(portfolio,index) of portfoliov1.data.slice(0,showNoOfPosts)" :key="index"
         class="col-sm-12 col-md-6 col-lg-4 ">
      <div class="overlay-wrap">
        <img :src="portfolio.image_path" alt="gallery images" class="img-fluid border-rad w-100" height="500"
             width="500"/>
        <a :href="portfolio.image_path" class="card-img-overlay primary-tp-layer pos-center text-center"
           data-fancybox="images">
                    <span class="center-holder">
                        <a class="ih-fade-down square-40 rounded-circle bg-white shadow-md">
                            <i class="fa fa-plus align-middle"></i>
                        </a>
                    </span>
        </a>
      </div>
    </div>
  </div>
</template>
<script>
import portfoliov1 from 'Components/data/portfolio-v1.json'

export default {
  props: ['showNoOfPosts'],
  data() {
    return {
      portfoliov1
    }
  }
}
</script>
   

I am looking for a way to dynamically display items based on the selected category using buttons. The goal is to filter out and display only items that match the selected category. Any suggestions on how this can be achieved?

Answer №1

To optimize your data handling, consider adding a filter variable within your data object:

  data() {
    return {
      portfoliov1,
      filter: ""
    }
  }

When a button is clicked, update the value of this variable accordingly.

<button class="active" @click="filter = ''">Show all</button>
<button @click="filter = 'Linens'">Linens</button>

Additionally, create a computed property to fetch the filtered data:

computed: {
  portfolio() {
    if (!this.filter) {
      return this.portfoliov1.data;
    }
    return this.portfoliov1.data.filter(p => p.category === this.filter);
  }
}

Your template will then be updated as follows:

<div v-for="(p, index) of portfolio.slice(0,showNoOfPosts)"

Additional suggestion:

In order to streamline your code, consider generating the buttons using a v-for loop like so:

<button v-for="category in categories" :key="category" :class="{ 'active': filter === category }" @click="filter = category" />
data() {
  return {
    // ...
    categories: ["Blanket", /* ... */]
  }
}

Note that handling the "no-filter" scenario is crucial.

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

When trying to use bootstrap modal buttons, they do not trigger with just a single click when

In my Angular code, I have implemented validation logic for when $locationChangeStart is fired. When this event occurs, I need to call event.preventDefault() to stop it and display a Bootstrap modal. However, I am encountering an issue where I have to clic ...

When ran automatically as a cron job, the JavaScript script fails to establish a connection with MongoDB

As I connect to mongodb (on a Ubuntu machine) from a js script, everything runs smoothly when I execute the command from the command line (node <name of the script>). However, when I try executing the same command from cron, the connection times out: ...

Is it possible to retrieve any user data by id using Vue 3 Firebase Auth?

I'm a newcomer to vue/firebase and I've been able to easily access the "current user" data from authentication. However, I am struggling to write a JavaScript composable that can retrieve the user object or at least displayName when passing in an ...

Transferring PHP array data to JavaScript using JSON

Hello there! I'm currently working with a PHP file that uses json_encode to encode an array. This file is then accessed by the jQuery ajax function to fetch the array. However, I'm having trouble understanding how to properly utilize the array. W ...

Use jquery ajax to upload an image with a reusable input field

UPDATE: Progress has been made in solving this issue. Please refer to Jquery form no submission to IE7 and IE8. The main task remaining is sorting out the compatibility with IE7 and IE8. I have been utilizing THIS plugin to upload files as email attachmen ...

Can $refs cause issues with interpolation?

I'm currently learning Vue.js and the course instructor mentioned that modifying the DOM element using $refs should not affect interpolation. In fact, any changes made directly to the DOM will be overridden by interpolation if it exists. However, in m ...

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...

The string array being sent to the WebService is being cut off

I created a C# WebApi method with the following signature: [HttpPost] [Route("getbyid/{date}")] public Response Get(DateTime date, [FromBody] List<string> ids) When testing this method using Postman and sending a list of strings in the body, everyt ...

Capable of retrieving the identification number but incapable of executing a POST request

After successfully retrieving the ID using the router, I encountered an issue when trying to confirm the change of agent status on the retireagent HTML page by clicking the submit button. The error message displayed is "ID is not defined". I am seeking ass ...

Guide to iterating over a set of data and retrieving the items based on specified query parameters

I'm currently working on querying data using nodeJS to extract custom information from a JSON file. My goal is to retrieve the most played games based on total playtime among users. Here is the JSON data: { "data": [ { "userId ...

Prevent the execution of useEffect on the client side in Next JS if the data has already been retrieved from the server

Upon loading the server side rendered page, data is fetched on the server and passed to client side components. To handle this process, a hook has been created with a state that updates based on checkBox changes. When the state changes, a useEffect is tri ...

Linkyfy.js does not function correctly with each and not statements

Trying to incorporate a linkifying script on a website, which transforms URLs in text into clickable links. Utilizing the following solution: https://github.com/SoapBox/linkifyjs To make it operational (post-download), the following steps are required: & ...

Guide on clearing the value of the first textarea and transferring it to the second textarea using JavaScript

I have encountered an issue where the first textarea value is being copied into the second textarea because I am using the same id for the 'add more' functionality. Below is the code snippet: <div id="divShortAnswerOption_Templated"> & ...

Creating a unique custom error message for every validation option

I am using a Joi schema and I would like to set custom error messages for each validation option. Here is an example of my schema: const schema = Joi.object().keys({ name: Joi.string() .min(5).error(() => 'first message') .ma ...

Express failing to deliver static content

I am currently facing an issue while trying to host a vue.js single page app using a node.js server. The problem seems to be related to some express middleware. Specifically, my struggle lies in serving two components - my index.html file and a dist folde ...

Transform JavaScript code into HTML using jQuery.`

I have a piece of HTML and JavaScript code. The JavaScript code is currently in jQuery, but I want to convert it to vanilla JavaScript: // Vanilla JavaScript code document.querySelectorAll('.hello[type="checkbox"]').forEach(item => { item ...

Having a problem with the glitch effect in Javascript - the text is oversized. Any tips on how to resize

I found some interesting code on the internet that creates a glitch text effect. However, when I implement it, the text appears too large for my webpage. I'm struggling to adjust the size. Here is the current display of the text: too big This is how ...

Steps for deactivating tab stops on the primary webpage in the presence of a snackbar

On my web page, there are multiple drop-down menus, input fields, and buttons that can be interacted with using both the tab key and mouse. After entering certain data, I trigger a snackbar (source: https://www.w3schools.com/howto/howto_js_snackbar.asp) t ...

Is there a way to create a function that is able to return both a value and a promise

Assume I need to fetch a value only if an object is already present in my model. Otherwise, I should retrieve the output of an endpoint service: model.getDoohkyById = function( id ){ if( this.data ) { if( this.data.length > 0) { ...

transferring information between GWT web application and App Engine backend (Java)

I am currently building a client with GWT and a server using App Engine. Our setup includes a mix of standard servlets and Restlet components. After following some guidance online, I have successfully utilized restyGWT on the client side for encoding and ...