Filtering select dropdown in VUE3 from an array or JSON data content

As a new user of Vue, I am facing an issue with filtering an array of 5/6 items using 3 select dropdowns. Currently, the filter data is only displayed when a button is clicked. I want to automatically display the filtered data without requiring a button click. This functionality needs to be implemented in Vue3. Click on this live site link for reference.

<template>
  <div>
    <h2>Users</h2>
    <div>
      <label for="foodType">Food Type:</label>
      <v-select
        id="foodType"
        v-model="selectedFoodType"
        :options="foodTypes"
      ></v-select>
    </div>
    <div>
      <label for="country">Country:</label>
      <v-select
        id="country"
        v-model="selectedCountry"
        :options="countries"
      ></v-select>
    </div>
    <div>
      <label for="district">District:</label>
      <v-select
        id="district"
        v-model="selectedDistrict"
        :options="districts"
      ></v-select>
    </div>
    <button @click="displayData">Display Data</button>
    <ul v-if="displayUsers">
      <li v-for="user in filteredUsers" :key="user.id">
        <p>Name: {{ user.name }}</p>
        <p>Food Type: {{ user.foodType }}</p>
        <p>Country: {{ user.country }}</p>
        <p>District: {{ user.district }}</p>
        <p>projectName: {{ user.projectName }}</p>
      </li>
    </ul>
  </div>
</template>

Javascript code:

import vSelect from 'vue-select'
import 'vue-select/dist/vue-select.css';
export default {
  components: {
    vSelect
  },
  data() {
    return {
      users: [
        { id: 1, name: "Aluino", foodType: "Swales", country: "japan", district: "Bigender", projectName:"LineOne" },
        { id: 2, name: "Ella", foodType: "Guitton", country: "Panama", district: "Female",projectName:"LineOne" },
        { id: 3, name: "Julina", foodType: "Tarbard", country: "USA", district: "Female",projectName:"LineOne" },
        { id: 4, name: "Walden", foodType: "McPhilip", country: "Brazil", district: "Male",projectName:"LineOne" },
        { id: 5, name: "Hillary", foodType: "Billingsley", country: "Norway", district: "Male",projectName:"LineThree" },
        { id: 6, name: "KKK", foodType: "McPhilip", country: "Brazil", district: "JJJ",projectName:"LineOne" },
        { id: 7, name: "LLL", foodType: "Billingsley", country: "Norway", district: "Male",projectName:"LineThree" }
      ],
      selectedFoodType: null,
      selectedCountry: null,
      selectedDistrict: null,
      displayUsers: false
    };
  },
  computed: {
    foodTypes() {
      return Array.from(new Set(this.users.map(user => user.foodType)));
    },
    countries() {
      return Array.from(new Set(this.users.map(user => user.country)));
    },
    districts() {
      return Array.from(new Set(this.users.map(user => user.district)));
    },
    filteredUsers() {
      let filtered = this.users;
      if (this.selectedFoodType) {
        filtered = filtered.filter(user => user.foodType === this.selectedFoodType);
      }
      if (this.selectedCountry) {
        filtered = filtered.filter(user => user.country === this.selectedCountry);
      }
      if (this.selectedDistrict) {
        filtered = filtered.filter(user => user.district === this.selectedDistrict);
      }
      return filtered;
    }
  },
  methods: {
    displayData() {
      this.displayUsers = true;
      console.log(this.displayUsers)
    }
  }
}
</script>

Answer №1

If I have grasped your message correctly, please review the following code snippet:

const app = Vue.createApp({
  components: {
    vSelect: window["vue-select"]
  },
  data() {
    return {
      users: [{ id: 1, name: "Aluino", foodType: "Swales", country: "japan", district: "Bigender", projectName:"LineOne" }, { id: 2, name: "Ella", foodType: "Guitton", country: "Panama", district: "Female",projectName:"LineOne" }, { id: 3, name: "Julina", foodType: "Tarbard", country: "USA", district: "Female",projectName:"LineOne" }, { id: 4, name: "Walden", foodType: "Tarbard", country: "Brazil", district: "Male",projectName:"LineOne" }, { id: 5, name: "Hillary", foodType: "Billingsley", country: "Norway", district: "Male",projectName:"LineThree" }, { id: 6, name: "KKK", foodType: "McPhilip", country: "Brazil", district: "JJJ",projectName:"LineOne" }, { id: 7, name: "LLL", foodType: "Billingsley", country: "Norway", district: "Male",projectName:"LineThree" }],
      displayUsers: false,
      selects: [{name: 'foodType', title: 'Food Type:', model: null}, {name:'country', title: 'Country:', model: null}, {name:'district', title: 'District:', model: null}]
    };
  },
  computed: {
    filteredUsers() {
      let filtered = this.users;
      const selectedFilters = this.selects.filter(s => s.model)
      selectedFilters.forEach(s => {
        filtered = filtered.filter(user => user[s.name] === this.selects[this.selects.findIndex(i => i.name === s.name)].model);
      })
      return filtered;
    }
  },
  methods: {
    selectOptions(type) {
      return Array.from(new Set(this.users.map(user => user[type])));
    }
  },
  mounted() {
    this.displayUsers = true;
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/vue-select@beta"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-select/dist/vue-select.css">
<div id="demo">
    <div>
    <h2>Users</h2>
    <div v-for="(sel, i) in selects" :key="i">
      <label :for="sel.name">{{ sel.title }}</label>
      <v-select
        :id="sel.name"
        v-model="sel.model"
        :options="selectOptions(sel.name)"
      ></v-select>
    </div>
    <ul v-if="displayUsers">
      <li v-for="user in filteredUsers" :key="user.id">
        <p>Name: {{ user.name }}</p>
        <p>Food Type: {{ user.foodType }}</p>
        <p>Country: {{ user.country }}</p>
        <p>District: {{ user.district }}</p>
        <p>projectName: {{ user.projectName }}</p>
      </li>
    </ul>
  </div>
</div>

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

whenever I execute my `node file.js 1 23 44` command, nothing is displayed on the screen

When I execute node file.js 1 23 45, the expected output is supposed to be One TwoThree FourFive. However, for some unknown reason, nothing is being printed out. The script appears to run without any errors, but the desired output is just not appearing. ...

Pass PHP date to JavaScript and increase its value

I'm looking to retrieve the server time with PHP and store it in a JavaScript variable. Once stored, I'd like it to continuously increment. Below is the code snippet: function initTime(date){ var today=new Date(date); var h=today.getHours(); v ...

Having trouble getting gulp set up and running with npm?

I am currently in the process of setting up gulp using npm in order to execute my project. Based on my understanding, all I need to do is enter "npm install gulp" in the command line at the location of my project like this : https://i.stack.imgur.com/hPU ...

Tips for creating a simulated comment section

To complete this task, you will be constructing a simulated comments section. Focus Our attention will be on two key elements: Users There are three types of users in this scenario - regular users, moderators, and admins. Regular users can only add new ...

angularJS transformRequest for a specified API call

Looking for a way to pass multipart/formdata through a $resource in Angular so I can post an image. I discovered a helpful solution on this Stack Overflow thread. However, the solution applies to all requests within my modules, and I only want it to apply ...

Modifying button styles in Angular UI Datepicker

In this plunk, there is an Angular UI Datepicker with a template. I'm trying to customize the colors of the "Today", "Clear", and "Close" buttons by editing the popup.html. However, even after changing the classes in the code, the datepicker still sho ...

What external libraries does Angular 4 utilize during execution, aside from RxJS?

Angular 4 relies on RxJS types in its public API and also internally depends on RxJS. It would be beneficial to explore if Angular utilizes other external packages for certain functionalities, allowing us to incorporate them into our own projects. This ap ...

How do I avoid using an if statement in jQuery to eliminate errors caused by "undefined" values?

Whenever I incorporate third-party plugins, my usual practice is to initiate them in the main application.js file. For example: $('.scroll').jScrollPane(); However, a challenge arises when a page loads without the presence of the scroll class, ...

Displaying text from a file on a webpage using HTML

I am a beginner in the world of html and javascripts. My goal is quite simple, I have a file stored on a server and I want to display the text from that file on my webpage. I found guidance on this forum post. Despite following the instructions provided, ...

How to recycle a texture in three.js?

Within my software, I come across numerous instances where I create geometries, each with its own meshing preferences (double-sided or not? Lambert or basic material?). Despite these variations, they all share the same texture. My goal is to load this comm ...

Troubleshooting issue with node.js 13 import functionality

$ node --version v13.8.0 We will now proceed to create three files: // package.json { "type": "module" } // foobar.js function foo() { console.log('foo') } export default {foo} // index.js import Foo from './foobar ...

Inheriting static functions

In my Node.js project, I have created a few classes as Controllers for handling routes. I would like these classes to work on a singleton basis, although it's not mandatory. Main Controller class class RouteController { static getInstance() { ...

Can one verify if an Angular application currently has active app modules running?

I am developing a unique plugin for Angular that is designed to automatically initialize an Angular app module if none are found. However, if there is already a running or declared ng-app, my plugin will utilize that existing module instead. Here is an i ...

Ways to extract information from JSON files

Currently, I am working on a script to extract viewer count and follower count data from Twitch. While I have successfully retrieved the viewer count information, I am encountering issues with extracting the follower count. The essential information can be ...

Interacting with AJAX links using Watir?

SOLVED: Resolved my issue by implementing this code snippet: b.link(id: 'm_wm_w5_m_lv_ctrl1_m_lnkWatch').fire_event :click QUESTION: Encountering difficulty clicking AJAX links using Watir. The specific element I am trying to click is located ...

What is the best way to utilize a computed property within a v-for loop?

I have a list for Vue, the second list is inside a wrapper with items on the left and right. computed: { currentIndex () { for (let i = 0; i < this.listHeight.length; i++) { let height1 = this.listHeight[i]; cons ...

Retrieve the Vue object nested within another object and log it in the console

I have a variable called 'file' in my Vue application. When I use console.log to inspect its contents, it displays as shown in the image below: console.log(file); https://i.sstatic.net/Zr2KL.png However, when I attempt to view the contents of ...

Utilize a select box to toggle between enabling and disabling options

Could someone please help me with enabling and disabling a text field based on a select box option? I'm not sure if I have written the code correctly below. If there are any errors, please correct me. <body> <table width="500" border="1"> ...

What is the reason behind only one function being executed out of the two in the onClick event?

I am currently developing a basic react application that involves passing multiple functions to update a shared state object in the parent component. However, I have encountered an issue where only one of the two functions appears to be executed when trigg ...

Naming build files with specific names in vue-cli3

Currently, with vue-cli3, whenever I run npm run build -- --mode=production, it generates 2 css files and 2 js files. After making a code change, the names of the files also change to something like app.de90cdf7.js and chunk-vendors.a9204242.js each time. ...