Manipulating prop values through dropdown selection

I'm currently working on implementing filtering based on a prop value that changes according to the dropdown selection.

Here's my progress so far:

template(v-for="field in tableFields")
   th(:id="field.name")

   select(@change="filterScope(scope)" v-model="selectedScope")
       option(v-for="scope in scopes" v-bind:value="scope" ) {{scope}}


template(v-for="(item) in tableData")
            row(
            :item="item"
            )

The first template is for the table header, and the second one is for the table rows.

Currently, my table displays data like this:

Name                  Age                  Gender
Andrew                 21                   Male
Dan                    21                   Male
Kate                   33                   Female

All the data in these rows are stored in the tableData variable, which is a prop whose value is defined by the parent component. I want to enable dropdown selection for Age and Gender.

For instance, the dropdown for age will have options 21 and 33. If I choose 21, the table should display as follows:

Name                  Age                  Gender
Andrew                 21                   Male
Dan                    21                   Male

My current code looks like this, and I'm uncertain about how to proceed further:

 methods: {
     filterScope: function(scope) {
            var resultArray = []
            this.tableData.forEach(function(data){
                if (data.age === this.selectedScope) {
                    resultArray.push(data)
                }
            }, this);
            this.tableData = resultArray;
        }
 }

The error I'm encountering is:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "tableData"

This approach doesn't seem to work due to both the incorrect data filtering and the Vue warning. How can I properly filter the tableData?

Answer №1

To prevent altering props, the use of `computed` property is recommended:

template(v-for="(item) in filteredData")
            row(
            :item="item"
            )

In the JavaScript code:

computed: {
  filteredData () {
    return this.tableData.filter((data) => data.age === this.selectedScope);
  }
}

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

What is the correct method for verifying the presence of a field in JavaScript (or its frameworks)?

Is there a better way to rewrite this computed method in JavaScript to handle cases where a field may not be available? computed() { isVerified() { return this.name.info.is_valid; } } I can make it less verbose, but I want it to still functi ...

I successfully made a GET request using Postman, but encountered an issue when trying to do the same request through a

Currently, my objective is to send URL encoded parameters through a GET request using the fetch function. To achieve this, I am attempting to display the parameters via Express in the following manner: app.get('/api', function (req, res) { c ...

Is the Vue2 Template compiler malfunctioning?

When compiling my code using webpack(^5.51.1) and vue-loader(^17.0.0), I encountered an issue while trying to run an older project. The error message displayed is as follows: [webpack-cli] Failed to load '/var/www/webpack.config.js' config [webpa ...

Concern raised about the challenge of removing an element from an array and its potential

When attempting to remove an element from an array without altering the state, I typically use the following code snippet: const tempArray = [ ...originalArray ]; tempArray.splice(index, 1); setOriginalArray(tempArray); After some experimentation, I deci ...

Using AJAX to communicate with a MySQL database and create a countdown timer using JavaScript

I have been trying to display data from a database using Ajax and incorporate countdown timers with times also fetched from the same database. It has been a struggle for me for almost 24 hours now. You can check out the main code here where you will notic ...

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

Incorporate personalized buttons into the header navigation for each view using VueJS

In my VueJS project, I attempted to include custom buttons in the sub navigation menu which could be customized for each view. Initially, I tried adding a simple property to the main data element, but that didn't yield the desired results. Then, I cam ...

Dynamic Character Measurement

I am currently utilizing Datatables to dynamically add rows to a table with 3 columns: Index Text CharCount I am seeking logic to implement a character count for each entry in the 'Text' column and display it in the corresponding 'CharCou ...

What is the process for inputting client-side data using a web service in ASP.NET?

Currently experimenting with this: This is my JavaScript code snippet: function insertVisitor() { var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>' $.ajax({ type: "POST", url: pageUrl + "/inse ...

What is the best way to integrate the express-session logic with Prisma for optimal performance?

Hi there, I recently started using Prisma and want to integrate it with PostgreSQL. My main goal is to implement authentication in my backend, but I encountered issues while trying to create a session table. When working with raw SQL, I managed to add the ...

Invoke a PHP function located in a separate file using a JavaScript function to fetch data from a database

How can I properly call a PHP function from a JavaScript function located in a different file? I am trying to pass a variable from an onClick function in JavaScript to a PHP function, which will then access a MySQL database to retrieve data. However, my c ...

Learn how to implement JavaScript code that allows a video to start playing only upon clicking a specific button

Within the confines of a div lies a <video autoplay> <source src='myvid'> </video>. This div initially has a display ='none' setting in its CSS. Upon receiving a click event, the display property changes from none to b ...

Using AJAX to remove data from a database

My PHP code snippet is displayed below: AjaxServer.php include '../include/connection.php'; // Check for the prediction if(isset($_POST["delete_me"]) && $_POST["delete_me"]=="true"){ $id = $_POST["id"]; $table = $_POST["table"]; ...

Customizing ExtJS 4.1: Mastering field overrides

Seeking guidance on applying a plugin to all fields(numberfield, textfield, datefield, etc.) within the ExtJS 4.1 library. Does anyone have suggestions on how to achieve this? I understand that all fields are derived from BaseField. I attempted the follow ...

TinyMCE - Utilizing selection.setContent along with getContent for the Warp Button

I am looking to implement a button that will wrap content with all tags. Snippet of Code: editor.addButton('MobileToggleArea', { text: '<M>', icon: false, onclick: function (){ editor.selection. ...

Send your information to a JSONP endpoint

Can data be posted to JsonP instead of passing it in the querystring as a GET request? I have a large amount of data that needs to be sent to a cross-domain service, and sending it via the querystring is not feasible due to its size. What other alternati ...

Utilizing PHP Variables in Jquery Ajax Success Response

I have a webpage that displays a list of routes. When a user clicks on a route, an AJAX request is sent to save the selected route in the database. On the same page, in a different tab, I am running a query to fetch related information about the selected ...

Vue: What is the best way to transfer data from a parent component to its child components?

Within my root component (app.js), I am trying to figure out how to pass down the activeTab data to Topbar. How can I achieve this within the app.js file? app.js window.Vue = require('vue'); Vue.component('Topbar', require('./c ...