Using Vue.js to sift through and refine data

I have retrieved data from an API and am displaying it here using VueJS. The user information is stored inside the users[] array, with two types of plans: basic_plan and standard_plan. Currently, all users are being shown.

Now I want to apply filters similar to this example: https://codepen.io/marn/pen/jeyXKL?editors=0010

I am also encountering an error stating that filter is not defined.

Filters:

  <input type="radio" v-model="selectedItems" value="All" /> All
                <input type="radio" v-model="selectedItems" value="basic_plan" /> Basic


<ul
            v-for="(user, index) in selectedUser.data"
            :key="index"
            class="watchers divide-y divide-gray-200"
        >
            <li class="py-4">
                <div class="mx-4 flex space-x-3">
                    <span
                        class="inline-flex items-center justify-center h-8 w-8 rounded-full bg-gray-500"
                    >
                      
                    </span>
                    <div class="flex-1 space-y-1">
                        <h3 class="text-sm font-medium">
                            {{ user.name }}
                        </h3>
                        <div class="flex items-center justify-between">
                            <p class="text-sm font-medium text-indigo-500">
                                {{ user.plan }}
                            </p>
                           
                            
                        </div>
                    </div>
                </div>
            </li>
        </ul>

       
    </div>
</template>

<script 
export default {
    data() {
        return {
            users: [],
             selectedItems:"All"
        };
    },
    created() {
        this.loadUsers();
    },
    methods: {
        loadUsers {
            axios
                .get('api/users')
                .then(response => {
                   
                        this.users = response.data;
                   
        }
    },
computed: {
        selectedUser: function() {
        
            if(this.selectedItems ==="All"){
                return this.users
            }else{
            return this.users.data.filter(function(item) {
                console.log(item)
                return item.plan === this.selectedItems;
            });
            }
        }
    }

};
</script>

When "All" is selected, the Vue dev tools show this:

selectedUser:Object //OBJECT SHOWING
data:Array[10]
links:Object
meta:Object
But when the "basic" radio button is selected, Vue shows this:

selectedUser:Array[1]  //ARRAY SHOWING
0:Object
price:"10"
plan:"basic_planl"

Answer №1

To exclude specific individuals, you need to utilize the "filter" function on the user variable in this way: this.users.filter(...)

Using this method, you can then sort users based on their subscription plan like so:

this.users.filter((user) => 
  user.plan === this.selectedItems;
});

I opted for a more contemporary approach by utilizing an arrow function. The absence of curly brackets signifies that the statement within the function is automatically returned, eliminating the need for a "return" statement.

Answer №2

Here is an alternative approach for you: since you are already utilizing v-for in your HTML, you can easily filter out users without additional loops. Make sure to check for the value "basic_plan" in the "user.plan" key.

I also recommend moving your v-for to the <li> tag instead of <ul>, and include validation on the <ul> if there are no users in the array.

<template>
    <div>
        <input type="radio" v-model="selectedItems" value="All" /> All
        <input type="radio" v-model="selectedItems" value="basic_plan" /> Basic
        
        <ul v-if="selectedUser.data.length" class="watchers divide-y divide-gray-200">
            <li v-for="(user, index) in selectedUser.data" :key="index" class="py-4">
                <div v-if="filterUser(user)" class="mx-4 flex space-x-3">
                    <span class="inline-flex items-center justify-center h-8 w-8 rounded-full bg-gray-500"></span>
                    <div class="flex-1 space-y-1">
                        <h3 class="text-sm font-medium">
                            {{ user.name }}
                        </h3>
                        <div class="flex items-center justify-between">
                            <p class="text-sm font-medium text-indigo-500">
                                {{ user.plan }}
                            </p>
                        </div>
                    </div>
                </div>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            users: [],
            selectedItems:"All"
        };
    },
    methods: {
        filterUser(user){
            if(this.selectedItems === 'All'){
                return true;
            }
            if(this.selectedItems === 'basic_plan'){
                return this.selectedItems === user.plan;
            }
        }
    },
}
</script>

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

Having a problem with file uploads in node.js using multer. The variables req.file and req.files are always coming

I am encountering an issue with uploading a file to my server, as both req.file and req.files are consistently undefined on my POST REST endpoint. The file I'm attempting to upload is a ".dat" file, and my expectation is to receive a JSON response. ...

Retrieve items from an array using a series of nested map operations

When I execute the query below, it transforms the json data into objects - 1st level being a map (This works fine as expected) const customerOptions = () => { return customersQuery.edges.map(({ node: { id, name } }) => { return { key: id, text ...

Ensuring Consistent Item Widths in a Loop using JavaScript or jQuery

In my code, I created a function that dynamically adjusts the width of elements in a loop to match the widest element among them. // Function: Match width var _so20170704_match_width = function( item ) { var max_item_width = 0; item.each(function ...

Unable to retrieve data from Meteor find query

I have a collection created in collections.js portfolioItems = new Mongo.Collection('portfolioitems'); This collection is then subscribed to in subscriptions.js Meteor.subscribe('portfolioitems'); And published in publications.js M ...

I'm looking to instantiate a Backbone collection outside of a script - how can I do that?

I have created my backbone collection named "Events" with a model called "Event". I want to create the backbone collection in this manner: Check out my code below: <script src="<?php echo site_url(); ?>js/backbone-calendar.js"></script&g ...

Swapping out the video in real-time using an on-demand script

Recently, I encountered an issue with my blog's YouTube video switcher. It seems that the videos won't play once they are changed, and it is related to a light YouTube embed script that I found here: . I believe this script was implemented to imp ...

Rails post with comments

Currently, I am in the process of developing a Rails application with Vue components integrated into multiple pages. To pass data to my Vue component, I use the following method: <v-my-component :posts="<%= @post.to_json %>"></v-my-componen ...

The object may be null even after being enclosed in an if statement

In my Vue component, I have implemented the following method: dataURLtoBlob(dataurl: string): Blob { const arr: string[] = dataurl.split(","); if (arr) { if (arr[0]) { const mime = arr[0].match(/:(.*?);/)[1]; ...

Using Vue.js class components to automatically update the view when the data in an RxJS Observable changes

Note: Just starting out with Vue.js here, and coming from an Angular background, I decided to go the Class Component route. I understand it may not be the recommended way in Vue.js, but this project is more of a fun experiment for me to try new things. Th ...

The steps to triggering a button click after e.preventDefault()

When attempting to prevent a click() event of a button by using preventDefault() after unbinding the button with unbind(), I encountered an issue where it did not work as expected. <script> $("#update2FAButton").on("click",function(e){ e.pre ...

Can I transfer a variable from JavaScript to Python in a seamless way?

Here's a straightforward query: Is it possible to include a JavaScript variable (varExample) in the data.py line while preserving the functionality of the JSONP Python callback code (?callback=? part)? The objective is to seamlessly integrate varExamp ...

Using Jquery to retrieve data in sections from a server and continuously add it to a file on the client side

I have a large dataset stored in JSON format on a Postgres Server with hundreds of thousands of rows. To prevent memory overload on the server, I need to provide users with the ability to download the data in chunks rather than all at once. This requires a ...

Encountering difficulties in updating CSS styles using the useState hook in React

I am currently working on creating a modal in react that changes the background color when opened. The goal is to have the background color darken when the modal is activated and return to normal when the modal is closed. I attempted to achieve this using ...

Encountering a JavaScript error in the backend of Joomla 3.2

I am facing an issue with buttons on my Joomla 3.2.3 sites in the backend. The save, edit (material, module, menu...) buttons are not working properly. These sites were deployed using Akeeba Kickstart. Interestingly, everything worked fine on the developme ...

What steps should I take to resolve the "StrictMode has found deprecated findDOMNode" error?

Whenever I trigger the button to open the drawer, my console displays the warning message '' findDOMNode is deprecated in StrictMode'' The container for the button component is called Sidenav import Sidenav from './Sidenav'; ...

The error message "There is no defined window.matchMedia prefers-color-scheme window in Next.js"

I am currently working on a project with React.js alongside Next.js and encountered an issue that I need assistance with. Upon loading the page, I need to set a variable that indicates whether the user is using dark mode or not. I attempted the following ...

The function has exceeded the time limit of 60000 milliseconds. Please make sure that the callback is completed

Exploring the capabilities of Cucumber with Protractor has been an intriguing journey for me. As I delved into creating a feature in Gherkin language, outlining the steps and scenarios necessary for my end-to-end tests, a new world of possibilities opened ...

Script on Tampermonkey executed prior to page loading

I am facing a challenge with hiding a specific section from an HTML page: <h1 data-ng-show="!menuPinned &amp;&amp; !isSaaS" class="logo floatLeft" aria-hidden="false"><span>XXX&nbsp;</span><span style="font-weight: bold;"& ...

The filtering function stops working after the initial use

As I develop an app using React and Redux, my goal for the following code snippet is to function as a reducer within the main application. I have imported a filterData function, which works seamlessly the first time any Action type is selected. However, it ...

Repeated URL causes Node to redirect

I am currently working on a project that involves redirecting users if they enter a specific URL, especially for redirecting from a Heroku domain. During my testing phase on localhost, I noticed that the redirect URL keeps getting repeated: http://localh ...