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

Struggling to access a PHP variable in a JavaScript file through AJAX

After studying numerous examples on how to pass a PHP variable to a JavaScript file, I have yet to successfully accomplish it. This is my PHP file: $title = $json["title"]; echo json_encode($title); And here is my app.js JavaScript file: $.ajax({ ...

No assets detected in sails.js

Recently, I began a new sails project using 'sails new project --linker'. Initially, everything was functioning correctly but today I encountered a problem. Every time I start the server with 'sails lift', I now receive a 404 error for ...

Can you explain the distinction between "(.....);" and "{......}" within the context of React?

Encountering an error indicated in the image for the following code: handlechange(event) { this.setState (prevState => { return( checked : !prevState.checked );}); } Interestingly, changing the round brackets after "return" to curl ...

Tips for incrementing a number by 1 at random intervals using jQuery

Is there a way to increase a number by 1 after an unpredictable delay? For instance, starting with a base value of 10, can we have it change by 1 after a random amount of time (e.g. between 1 and 5 seconds)? I attempted the following code: var ...

The function(result) is triggered when an http.get request is made

Can anyone help me figure out why my function is jumping after completing the request? It seems to be skipping over .then(function(result){ }. I suspect that the issue might be related to the <a> element with an onclick attribute containing an href ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. The content provided was considered valid. An error is thrown based on the specified pattern. However, it should als ...

iOS device encounters failure with Ajax CORS request and redirect

I am experiencing an issue where a URL is being redirected to another domain by the server. My test code is very simple: $.ajax({ type:"GET", url:"{MYURL}", success:function(d){alert('response');} }) You can che ...

I am looking to consolidate my array of objects into a single object with distinct keys

Hey there! I'm looking to showcase the expenses for each category throughout the months of the year. Here's an example: {Month: "January", Food: 610, foodColor: "#063951", Others: 121, othersColor: "#C13018", …} Fo ...

Refreshing a component in React when a prop changes

My understanding is that React components update when their props or state change. For example, I declare a variable like this: let percentage = { width: '10%', }; Then, I have a function using setInterval to upd ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

Is there a way to retrieve two distinct data types from a single ng-model within a select option?

My mean stack code is functioning well, but I am looking to enhance it by adding a new feature. Specifically, I want to retrieve more elements from my NoSql database while selecting options. This is the structure of my database: Tir2 :id, price, xin, yin ...

Steps for transferring JSON data from the controller to JavaScript

Within my cluster Table, there is a column called description which stores cluster coordinates in JSON format. I want to draw multiple cluster polygons on Google Maps using these coordinates. id | description ...

Introducing additional choices to the list and automatically refreshing the list with the latest updates

I am currently honing my skills in Yii2 by working on a project using this framework. One of the challenges I am facing is adding new list options dynamically without having to navigate away from the current page. When I click the "Add new option" button ...

The primary origin of TypeScript is derived from the compiled JavaScript and its corresponding source map

Being new to sourcemaps and typescript, I am faced with a project that has been compiled into a single javascript file from multiple typescript files. The files available to me are: lib.js (the compiled js code of the project) lib.js.map (the source map ...

Enhance your website's accessibility by using JavaScript to allow the down and up arrow keys to function

Thank you for taking the time to read this, any feedback is greatly appreciated. The current script on my website is only partially functional (click "i" in the bottom right corner). Currently, the script will focus on the first link AFTER pressing the T ...

Error: Unexpected token : encountered in jQuery ajax call

When creating a web page that requests remote data (json), using jQuery.ajax works well within the same domain. However, if the request is made from a different domain (e.g. localhost), browsers block it and display: No 'Access-Control-Allow-Or ...

Who is the intended audience for the "engines" field in an npm package - consumers or developers?

As the creator of an npm library, I have included the current LTS versions of Node.js and npm in the package manifest under the engines field. This ensures that all contributors use the same versions I utilized for development: Node.js <a href="/cdn-cgi ...

Display a confirmation modal before triggering $routeChangeStart in AngularJs, similar to the window.onbeforeunload event

When a user chooses to stay on the page as the route starts to change, the original route remains intact but the form directives are reloaded. This results in the loss of all checkbox and input values, resetting them to their defaults. If a user closes th ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

Aborting HTTP POST requests in IE due to error code 0x2ee2

Currently, I am utilizing angularjs for file uploads to my API. The page features a multi-file select option where users can choose one or multiple files. Upon selection, the page initiates calls to the api and uploads each file individually using requests ...