How to trigger a click event on a div and effectively filter Vuex data in Vue.js?

Currently facing a challenge with exporting the filter function and utilizing it in a vuex store. Everything was smooth sailing until this point. Now, I'm attempting to add an @click event to divs. When I click on a particular brand, such as "Audi," I want the filter to display only "Audi." If I click on "Audi" again, it should remove it from the filter.

Here is the sandbox link to explore more: https://codesandbox.io/s/filtering-bzphi

filter.js

export const carFilter = car => allcars => {
      if (car.length > 0) {
        if (allcars.name.includes(car)) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    };

Store

export const store = new Vuex.Store({
  state: {
    cars: [
      { name: "AUDI" },
      { name: "BMW" },
      { name: "MERCEDES" },
      { name: "HONDA" },
      { name: "TOYOTA" }
    ],
    carBrand: []
  },
  mutations: {
    updateCarsFilter(state, carBrand) {
      state.carBrand = carBrand;
    }
  },
  getters: {
    filteredCars: state => {
      return state.cars.filter(carFilter(state.carBrand));
    }
  }
});

and App.js

<template>
  <div id="app">
    <div class="boxes" :key="index" v-for="(item, index) in cars">{{item.name}}</div>
    <List/>
  </div>
</template>

<script>
import List from "./List.vue";
export default {
  name: "App",
  components: {
    List
  },
  computed: {
    selectBrand: {
      set(val) {
        this.$store.commit("updateCarsFilter", val);
      },
      get() {
        return this.$store.state.carBrand;
      }
    },
    cars() {
      return this.$store.getters.filteredCars;
    }
  }
};
</script>

For a clearer insight, I've set up a sandbox. Feel free to refer to it: https://codesandbox.io/s/filtering-bzphi

Answer №1

In the store.js

  • Modified the default value of carBrand to ''
  • Introduced a Mutation called clearFilter
  • Implemented a Getter named isActiveFilter

Update:

  • Removed carBrand from the state
  • Added selectedCars as an array to replace carBrand
  • Eliminated the mutation related to carBrand
  • Added mutations for addCarSelection and removeCarSelection
  • filteredCars will now return the selectedCars array if cars are present, otherwise it returns the state of cars
  • Introduced isSelectedCar to verify if a car is in the selection

The function carFilter from filter.js is no longer necessary.

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    cars: [
      { name: "AUDI" },
      { name: "BMW" },
      { name: "MERCEDES" },
      { name: "HONDA" },
      { name: "TOYOTA" }
    ],
    selectedCars: []
  },
  mutations: {
    addCarSelection(state, car) {
      state.selectedCars.push(car);
    },
    removeCarSelection(state, car) {
      state.selectedCars = state.selectedCars.filter(r => r.name !== car.name);
    }
  },
  getters: {
    filteredCars: state => {
      if (state.selectedCars.length !== 0) {
        // There's selected cars, return filtered
        return state.selectedCars;
      } else {
        return state.cars;
      }
    },
    isSelectedCar: state => car => {
      return state.selectedCars.some(r => r.name === car.name);
    }
  }
});

In the App.vue

  • Added a method called filterCars (moved from the computed property searchText)
  • Included a method clearFilter

Update:

  • Removed filterCars and 'clearFilter' method and linked new mutations and getters from the store
  methods: {
    addCarSelection(car) {
      this.$store.commit("addCarSelection", car);
    },
    removeCarSelection(car) {
      this.$store.commit("removeCarSelection", car);
    },
    isSelectedCar(car) {
      return this.$store.getters.isSelectedCar(car)
    },
  }
  • Added a computed property called isFilterActive()

Update:

  • Removed isFilterActive() and searchText from the computed properties
  computed: {
    cars() {
      return this.$store.getters.filteredCars;
    },
  },

Update:

  • Modified the Template code to handle the @click event for adding or removing a car from the selection
  • The boxes always display the available cars; if isSelectedCar is true, it toggles between the add or remove function.

  • The list shows the selected cars if they are present; otherwise, it displays the complete car catalog.

<template>
  <div id="app">
    <div class="boxes" :key="index" v-for="(item, index) in cars">
      <div
        v-if="!isSelectedCar(item)"
        style="cursor:pointer"
        @click="addCarSelection(item)"
      >{{item.name}}</div>
      <div v-else style="cursor:pointer;" @click="removeCarSelection(item)">
        {{item.name}}
        <small>[x]</small>
      </div>
    </div>
    <List/>
  </div>
</template>

Updated version is now available in this sandbox

https://codesandbox.io/s/filtering-3ej7d

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

Is it possible for a div nested within another div to still occupy space on the page despite being set

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $("select#choosebook").change(function(){ $(".title").slideDown(" ...

Steer clear of utilizing Number() when working with scientific notation

I am attempting to perform the following task Number("0.00000000000122") yields 1.22e-12 However, my goal is to convert that number from a String to a Number. console.log(Number("0.00000000000122")) ...

object passed as value to competent parent

I'm facing an issue where I am trying to pass a value to the parent component, but it is returning an object instead of the expected value. Here's what I have: Child Component render() { return ( this.props.data.map((val, idx) => { ...

Concealing information based on the value of a variable

Creating a dynamic price estimator. I need help writing a jQuery function that can hide or show a specific div element based on the value of a variable. For example, let's say I have an HTML div with the ID 'Answer': <div id="answer"&g ...

Scrolling to the top of the Popper component when an element is selected

I am currently utilizing the Autocomplete Material UI control with multiple selections enabled. Here is the code snippet I have created based on this answer: <Autocomplete PopperComponent={PopperMy} ... /> const PopperMy = function (props) ...

Choosing the content within a div and inserting it into an email

I have an email sender feature on my website where users can fill out input fields and hit send, resulting in me receiving an email. The text from all the input boxes is included in the email body. Additionally, there are some generated texts in divs with ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

Encountering an error message related to Bootstrap carousel: "Unable to read property 'offsetWidth' of undefined"

Encountering a frustrating error message: "Cannot read property 'offsetWidth' of undefined" when using Bootstrap carousel. Let me share my code with you: <div id="myCarousel" class="carousel slide" > <ul class=& ...

I require the use of Nodejs with the gm module to process images, but it is essential that it

There are two methods to consider, but I am struggling to make it synchronous. Despite attempting to use Promise.all to synchronize the process, I am faced with the challenge of images processing asynchronously and inability to reject or resolve in a loop. ...

Iterate through each row of the PHP array

Hey there, I have two sets of code that I'd like to share with you. The first one is an Ajax snippet: /* Loop and Retrieve Data from Database to Generate a Table */ $(document).ready(function () { $('#btngenerate').click(function(e){ ...

Verify the validity of a form using JavaScript and by utilizing HTML5 validation, then proceed to save the form data in local storage

I'm fairly new to working with JavaScript and jQuery. Currently, I am attempting to validate the HTML5 validation of a form using JavaScript. When the form is valid, I want to save the data in localstorage WITHOUT having to reload the webpage. Here is ...

What are the specific extensions for email validation?

code for the form: <form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" > <p class="email"> <label for="budget">Expected Budget ...

When a jQuery click event is triggered, the event.target will return the child element that was clicked within the

When I have a jQuery click event assigned to a hyperlink that contains an image, each with separate ids, I expect clicking the hyperlink to trigger the code event.target.id, returning the hyperlink's id. However, it actually returns the image's i ...

<use> - SVG: Circles with different stroke properties

Why is the stroke of both <use> elements being ignored here? The stroke color of <circle> is set to blue, which is also appearing on both <use> elements. Why? I am trying to set different stroke colors for all three of these elements, bu ...

Discovering the orientation of an object in relation to the camera

I'm encountering a challenge in determining the angle of an object in relation to the camera. My goal is to write code for a spaceship with a camera that follows it. While I have successfully made the camera track the ship, there are instances where t ...

jQuery animation for expanding accordion headers

I want to create a cool animation for my accordion headers that mimics a ribbon being dragged onto the wrapper when hovered over, and then dragged out when the hover ends. Everything was working fine in this initial jsFiddle, but as soon as I tried to ani ...

What causes axios to return a z_buf_error?

I've encountered an issue with axios returning an error cause: Error: unexpected end of file at BrotliDecoder.zlibOnError [as onerror] (node:zlib:189:17) { errno: -5, code: 'Z_BUF_ERROR' I'm puzzled as to why this functio ...

having trouble parsing JSON data

Recently, I decided to experiment with JSON and utilized json_encode to generate a JSON object structured as shown below: [{ "timestamp": "12\/16\/2013 0:00", "curr_property": "7211", "curr_property_cost": "123", "day_pro ...

Is there a way to retrieve bookmarks (TOC) from a PDF document using technologies such as NodeJS, ReactJS, or PHP?

I'm sure most people have noticed that when you open a PDF in the browser or Acrobat PDF reader, a bookmarks tab appears like the one shown here: https://i.stack.imgur.com/obFer.png If the PDF doesn't have any bookmarks, the list will be empty. ...

Obtaining a String from a Nested Array through Nested Iterations

As someone who is just starting out with coding, I am currently focused on practicing loops and arrays. One of my exercises involves working with an array that contains multiple sub arrays, each of them consisting of pairs of strings. My goal is to extract ...