Vue.js filters items based on their property being less than or equal to the input value

I'm currently working on a project in vue.js where I need to filter elements of an object based on a specific condition.
I want to only return items where maxPeoples are greater than or equal to the input value.

Below is a snippet of my code: model:
template:

<template>
  <div id="app">
    <Titre />
    <div class="flex justify-around" v-if="maxPeoples === ''">
      <input type="text" v-model="maxPeoples" placeholder="set maxPeoples" @keyup.enter="setMaxPeople">
      <div v-for="recipe in recipes" :key="recipe.id">
        <recipe :picture="recipe.picture" :title="recipe.title" :preparation="recipe.preparation" :people="recipe.people" />
      </div>
    </div>
  </div>
</template>

script:

export default {
  name: 'App',
  data() {
    return {
      maxPeoples: '',
      recipes: [
        {
          id: 1,
          picture: 'https://picsum.photos/id/100/100/60',
          title: 'Macaronis au fromage',
          preparation: 15,
          people: 2
        },
        {
          id: 2,
          picture: 'https://picsum.photos/id/110/100/60',
          title: 'Croque-monsieur',
          preparation: 10,
          people: 1
        }
      ]
    }
  },
  methods:  {
    setMaxPeoples(maxPeoples){
      this.recipes.filter(recipe => recipe.people >= maxPeoples);
    }
  }
}

I'm encountering an error message:

Failed to compile.

./src/App.vue
Module Error (from ./node_modules/eslint-loader/index.js):

C:\Users\rollivier\Desktop\Franck\dicolor\vue\test-vue\src\App.vue
  75:29  error  'recipe' is defined but never used  no-unused-vars

✖ 1 problem (1 error, 0 warnings)

I suspect that the forEach loop is causing the issue...
Thank you for your help.

Answer №1

If you want to retrieve a list of recipes where the number of people is less than maxPeoples, you can achieve this by using a computed list.

computed: {
  filteredRecipes() {
    const filtered = this.recipes.filter(recipe => recipe.people < this.maxPeoples)
    return filtered
  }
}

You can then use it in your code like this,

<div v-for="recipe in filteredRecipes" :key="recipe.id">

I recommend adding validation for the maxPeoples input to ensure that only numerical values are allowed. You can do so with the following:

data() {
  return {
    _maxPeoples: ''
  }
},
computed: {
  maxPeople: {
    get() {
      return this._maxPeoples
    },
    set(value) {
      if (validate(value)) {
        this._maxPeoples = value
      }
    }
  }
}

Answer №2

My recommendation would be to eliminate the

@keyup.enter="setMaxPeople"
and v-model since it involves two-way binding where values are being set from different sources -
@keyup.enter="setMaxPeople"
and v-model= "maxPeoples"

For better practice, I suggest replacing it with

<input 
type="text" 
:value="maxPeoples" 
@input="setMaxPeoples()" 
placeholder="set maxPeoples">

Further, update your method to:

setMaxPeoples(){
    this.maxPeoples = event.target.value
     this.recettes.forEach(recipe => {
        if (recipe.people <= this.maxPeoples) {
        // console.log(recipe.people)
          return recipe.people
        } else return false
      })
    }

To enhance this, you can create a separate computed property for maxPeoples

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

I am attempting to arrange variables based on the key of the json nested within another json

It's a bit challenging to condense my goal into one question, but I'll try my best to clarify. I currently have a JSON array that represents various HTML slider elements categorized within 3 control panes: Basic, Interface, and Advanced. Each pa ...

The jQuery hide and show functions lack precision and are too indiscriminate, requiring a more targeted approach

I am designing a unique contact card that captures a user's name and description from an <input> field and appends the input information into a <div> element. This is the flow I am aiming for... User inputs their first and last name alo ...

Converting user input from a string to an object in JavaScript: a comprehensive guide

Is there a way to transform user input string into objects when given an array of strings? ["code:213123", "code:213123", "code:213123"] I am looking to convert this array into an array of objects with the following format: [{code: "213123"},...] ...

Inspecting element value on a website

On a marketplace website, I extracted the attribute (capacity_gold) from a table. Since the values are dynamic and constantly changing, I aim to develop a basic script that will notify me when the attribute value exceeds 100. The current value of the attr ...

``The Vue.js routing system is determined by the incoming data received

Working with VueRouter to navigate to a component based on payload. { path: '/foobar', name: 'foobar', component: foobar, } { path: '/foobar', name: 'foobarSuccess', component: foobarSuccess, query: { ...

Tips for manipulating the DOM: Pushing existing elements when new ones are dynamically created with JavaScript

I have a pre-existing DOM element (let's say a div) and I am using JavaScript, specifically React, to create a new element - another div which serves as a sidebar. The goal is for the sidebar to seamlessly shift the previous element without overlappin ...

Using async/await to handle the callback function

Here is a function that saves a user in the database: exports.saveUser = ({ first_name, last_name, email, password }) => { const query = "insert into users (first_name, last_name, email, password_hash) values ($1, $2, $3, $4) RETURNING *"; ...

When using vue-property-decorator, changes in data do not automatically generate an `emit` event

I have created a selection field that showcases a variety of fruits. My goal is to update the parent component with the selected fruits from the SelectAll feature. To achieve this, I implemented a component event called @Emit("fruitsSelected") which should ...

The sorting icon in jQuery Data Table's search option is not functioning

I am having an issue with jQuery DataTables. When using jQuery DataTables, it provides a default search option. However, the problem arises when I search for a particular record and if the content does not match or if I find a single record, then I need to ...

Combine two JSON objects which share a common attribute

I am currently working with two JSON feeds. One feed contains the basic information about a course, while the other contains more administrative details. Here is an example to illustrate what I mean. FIRST {"courses": {"course":{"id":"4","title":"Usi ...

Uncover the structure of a regular expression pattern to discover the quantity of tokens and the size of the anticipated matches

I am looking to validate certain fields in my forms by determining the number of tokens and length specified by a particular regular expression. For example, For the pattern [0-9]{3},[0-9]{2}, I need to identify 5 as the length and 2 as the number of to ...

What is the best way to modify a particular value buried within a JavaScript object?

Within my node project, I am working with a JavaScript object like the one shown below: that.responseData = { fields: { id: { label: 'ID', value: objectRecord.id, info: '', ex ...

Techniques for transferring images directly into HTML canvas games

I created a thrilling race car game and here is the code snippet: index.html <!DOCTYPE html> <html> <head> <title> Extreme Race Car Game </title> <link rel="stylesheet" type="text/css" href="style.css"> < ...

Ways to retrieve nested data from an object

I have added an object with categories in a database. It displays the price and date of addition. How can I output the date to the console? Currently, in the console, it shows: [ [ { cost: '50$', date: [Object] } ] ]. I need to extract the inform ...

Is there a way to ensure that the line numbers displayed for JavaScript errors in Chrome are accurate?

I suspect either my webpack configuration or my npm run dev script are causing the issue, but I'm unsure of what exactly is going wrong. While running my application in development mode, I encounter error messages like: Uncaught TypeError: this.props ...

What is the best way to extract the image url from a page in WordPress?

Is there a way to extract the image URL in WordPress dynamically for use as a reference in a script? When I use postimage(); it extracts this: <a href="address"> <img width="300" height="300" src="image.png" class="image" alt="" title="LINKING"/& ...

Tips on transforming truncated surfaces into complete entities

When working in Three.js, I encountered a situation with a 3D object where local clipping planes were used to render only a specific part of the object. However, due to the nature of 3D objects being "hollow" (only rendering the outer surface), when somet ...

Removing a row from a table in AngularJS connected to FireBase

I am currently facing an issue where the function fails to work when attempting to delete a row. My goal is to be able to remove a specific row from the table by clicking on the red button. Here is the link to my plunker code In index.html, I have includ ...

Determine in JavaScript whether a character is 32-bit or not

Is there a way to determine if a specific character is 32 bits using JavaScript? I attempted to use charCodeAt() but it was unsuccessful for identifying 32-bit characters. Any guidance or assistance on this matter would be greatly valued. ...

Creating a sort button in HTML that can efficiently sort various divs within a table is a useful tool for enhancing user experience

My HTML table is populated with various <td> elements. How can I arrange these divs based on IMDb rating, TomatoMeter, etc... [ CSS code is not provided below ] <table> <tr class="row"> <td class="column"> <br> ...