Implementing Vue method to apply filter criteria on an array for efficient data filtering

Having trouble filtering listItems by filterCriteria before rendering.
The issue arises when attempting to pass the filterCriteria into the filter function using Array.prototype.filter.
Is there a more efficient method of passing it without having to create a new function?
Thank you!

Answer №1

...struggling to pass the filterCriteria into the filter function. Is there any way to do it efficiently without having to create a new function?

A solution is available. Firstly, you can use an arrow function for the callback:

filtered () {
  return this.items.filter(item => item.status === this.query)
}

Alternatively, you can retain a reference to the this object:

filtered () {
  var vm = this
  return this.items.filter(function (item) {
    item.status === vm.query
  })
}

Here is a complete example:

var todoList = new Vue({
  el: '#todolist',
  data: {
    query: 'Done',
    items: [
      {content: 'Fishing.', status: 'Done'},
      {content: 'Do homework.', status: 'Ongoing'}
    ]
  },
  computed: {
    filtered () {
      return this.items.filter(item => item.status === this.query)
    }
  }
})
<div id="todolist">
  <div>
    <button @click="query='Ongoing'">Ongoing</button>
    <button @click="query='Done'">Done</button>
  </div>
  <div v-for="item, idx in filtered" :key="idx">
    <span>{{item.status}}:</span>
    <span>{{item.content}}</span>
  </div>
</div>

<script src="https://unpkg.com/vue"></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

Prevent redundant Webpack chunk creation

I am currently working on integrating a new feature into my Webpack project, and I have encountered a specific issue. Within the project, there are two entry points identified as about and feedback. The about entry point imports feedback, causing both abo ...

Guide on Generating SAS Token for Azure Table Storage in a jQuery Application

I am currently working on a jQuery web application that requires read-only access to an Azure Table Storage, fetching one record at a time by passing in the PartitionKey and RowKey. To simplify my code, I have integrated the Azure Storage JavaScript Client ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

Why is it important to incorporate an inner function in order to return to the outer function?

Can you explain the distinction between these two functions, bind_1 and bind_2? function bind_1(f, o) { if (f.bind) return f.bind(o); else return function() { return f.apply(o. arguments); }; } function bind_2(f, o) { if (f. ...

Is there a way to calculate the word frequency in my text using plain JavaScript?

Welcome to the text entry section: https://i.sstatic.net/VlBvt.png After clicking on the COUNT button, it will direct you to this page: https://i.sstatic.net/sqKWc.png I can see my entered text and word count displayed. Now I'm curious, how can I ...

When an if statement is triggered by an overload of information, it initiates the start of a fresh

I am in need of creating an if statement that will trigger whenever images with IDs 0 to 3 (a total of 4 images) are loaded. This if statement should then generate a new row containing 0 to 3 images, and the same logic needs to be applied for words as well ...

I'm encountering an error in my routes index.js file that says "Module not found"

The issue is stating "Cannot find module './routes/index'" despite it being located in that directory (even when static is set to that folder) Here is the error: root@ip*censored*:/home/ubuntu/*censored*# module.js:471 throw err; ^ Err ...

transform array elements into an object

I encountered the following code snippet: const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map( (cssClass) => { return { [cssClass]: true }; } ); This code block generates an array of objects like ...

Signing in using Passport.js with mongoDB authentication

Apologies if this question appears redundant, but I am struggling to resolve an issue with a "MISSING CREDENTIALS" error when trying to implement user login using email and password. Despite going through numerous responses, none have provided a solution. ...

What will occur if I invoke response.end in Node.js while asynchronous I/O operations and callbacks are still executing?

When working with Node.js, what happens if you call "response.end()" while I/O calls and/or callbacks are still being executed? Take a look at the code snippet below: var app = http.createServer(function(request, response) { response.writeHead(200, { ...

I have encountered a node.js error related to the 'Require Stack'

Encountering an error in my node.js application when trying to open a .js file { code: 'MODULE_NOT_FOUND', requireStack: } Unable to determine the root cause of this issue I have tried re-installing Node.js and its packages, removed and added b ...

Create a minimalist Vue table design that enforces a maximum of 2 or 3 columns within

Is there a way to make my v-simple table with v-chips and v-badges align correctly in two or three column peer cell format? Here is the table for reference: https://i.sstatic.net/OFCyx.png Currently, I only have scoped styling applied: <style scoped> ...

Check to see if the menu item exceeds the allotted space, and if so, display the mobile menu

Currently, I am in the process of creating a unique responsive menu for my website that I think will need some JavaScript implementation. My skills with JavaScript are not very strong, so I am looking for guidance, code examples, or resources that can assi ...

Retrieve Data from Form Using PHP and Ajax

I currently have a form on my HTML page that looks like this: <form id="submission" action="testresponse.php" method="post"> <input id="URL" name="URL" type="text"> <button name="Submit" type="submit">Subm ...

function to draw a table row in JavaScript with eloquent and descriptive arguments

I came across this code in chapter 6 of a programming book called "Eloquent JavaScript". I am struggling to understand where the arguments for the function 'drawRow' are coming from. If the outer function drawTable was a method, it would make sen ...

How to send and download files using Express.js and React on the client side

Currently, my backend is built with Express JS and the frontend with React JS. In certain routes, I need to send a file in response to requests. Here's how I'm currently handling it: return res.status(200).sendFile(path.resolve(`files/${product. ...

The Google Maps JavaScript API is displaying a map of China instead of the intended location

After multiple attempts, I am still facing an issue with setting up the Google Map on my website. Despite inputting different coordinates, it consistently shows a location in China instead of the intended one. Here is the code snippet that I have been usin ...

Unable to invoke requestPointerLock() function within Vue.js component

Incorporating the requestPointerLock() method within a Vue.js component has posed some challenges for me. In the scenario where the pointerShouldLock data property of my component is set to true, I intend for the pointer to be locked during the beforeUpdat ...

Techniques for dynamically counting rows in a table using JavaScript

I'm working on a system to create and delete rows, and I want each row to have a unique row number displayed under "Num." However, I'm having trouble implementing this feature. EDIT I found a jQuery snippet that counts the first row but not t ...

Utilizing Anglar 16's MatTable trackBy feature on FormGroup for identifying unaltered fields

In my application, I am working with a MatTable that has a datasource consisting of AbstractControls (FormGroups) to create an editable table. At the end of each row, there are action buttons for saving or deleting the elements. My goal is to implement tr ...