Observing nested data changes in Vue.JS?

In my Vue.js components, I have a group of checkboxes that are sending data to the parent element. My goal is to monitor this data for changes and use it to filter information in an API call.

When certain checkboxes are selected, the data stored on the parent element looks like this:

https://i.sstatic.net/aCz9T.png

I aim to incorporate this data into an API request that would follow this format when the data changes:

this.axios.get('http://localhost:8000/api/v1/schools' + 
    for (feature in selectedFeatures) {
        '?features[]=' + feature
    }
).then((response) => {
    this.$root.$emit('searchQuery', response.data);
});

Typically, using Vue's Watch functionality makes this task simple. However, due to the nested structure of my dynamic arrays, I am unsure how to achieve this.

Answer №1

To resolve the issue, I made a modification to the code in Filters.vue as follows:

methods: {
    addFeatures() {
        var featureNames = '';
        // Iterate through selectedFeatures and create a string of all features
        for (var key in this.selectedFeatures) {
           var obj = this.selectedFeatures[key];
           for (var prop in obj) {
               // Remove spaces and add + sign
               featureNames += '&features[]=' + obj[prop].split(' ').join('+');
           }
        };
        return 'http://localhost:8000/api/v1/schools?' + this.selectedGrade + '=1' + featureNames;
    }
},
mounted() {
    // Trigger new API call when checkUpdated is emitted
    this.$root.$on('checkUpdated', function() {
        var gradeFeatures = this.addFeatures();
        // Append result from addFeatures method to end of API URL and send it to root to filter data
        this.axios.get( gradeFeatures ).then((response) => {
            this.$root.$emit('searchQuery', response.data);
        });
    }.bind(this));
}

In addition, I made a slight change to Checkbox.vue by updating:

<input type="checkbox" :disabled="disabled" :name="name" v-model="newValue" @change="$emit('change', newValue, $event)">

to:

<input type="checkbox" :disabled="disabled" :name="name" v-model="newValue" @change="valueChanged">

I also added:

methods: {
    valueChanged() {
        this.$root.$emit('checkUpdated');
        this.$emit('change', this.newValue, this.$event);
    }
}

The mounted lifecycle in Filters.vue can then detect these changes and trigger the method accordingly.

This solution works effectively!

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

Is there a way to fully break out of a .forEach loop that's nested within a function?

Here is the method I am currently working with: wordFormDirty = (): boolean => { var self = this; angular.forEach(self.word.wordForms, function (wf, key) { var wordFormNgForm = 'wordFormNgForm_' + wf.wordFormId if ...

Ways to extract information from a dynamically loaded webpage

Is there a way to extract data from a news website that automatically reloads at set time intervals? I want to use this data on my own website as information, whether it's in the form of images or text. Can anyone guide me on how to retrieve data from ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

When the add button is clicked, I would like to implement a feature where a checkbox is added

When the user clicks on the link "출력하기", I want the web page to add a checkbox to all images. I wrote this code, but it's not working. Can anyone help me? This is my JS: $(document).ready(function(){ $("#print").on('click', fu ...

I'm feeling a bit lost on where to go next with this JavaScript

I've been working on a project in Python where I need to retrieve a file, store it in an array, and display a random string from the array on HTML. However, I have no experience with JavaScript and am unsure how to proceed. I suspect there may be an i ...

Aligning the second heading alongside pictures and a lightbox

My issue is that I am struggling to center the "See More" link directly under each title link. Currently, it is pushed to the right and I can't seem to find a solution. Any help with this problem would be greatly appreciated. I attempted using display ...

javascript - determine whether a hyperlink has been accessed

Is there a method to determine if a link has been visited? In Firefox, the color of a link changes after clicking on it, which leads me to believe it is possible. Edit: This question pertains to a Firefox extension, so I am unable to modify the HTML or CS ...

invisible recaptcha with synchronous ajax

Hey, I'm trying to figure out a solution on how to obtain the token or a valid response from Recaptcha and then proceed with running the ajax call. Does anyone have any suggestions on how to achieve this in a synchronous manner? Here's the proce ...

Bizarre Angular directive nesting issue discovered after upgrading from version 1.4.9 to 1.5.0

Forgive the unclear title; I am still trying to pinpoint exactly what is causing issues after the upgrade. Could it be a problem with nested directives or template inconsistencies? (see sample images & links to CodePens below) Issue I have a basic o ...

The OnChange event seems to be malfunctioning as it is not being triggered despite other parts of the code functioning properly

Check out the code snippet below: import React, { useState } from "react"; function IP() { const [ipAddress, setIPAddress] = useState(""); const handleInputChange = (event) => { const inputValue = event.target.value; // ...

Is it worth diving into Vue.js, Angular, or React while utilizing Laravel currently?

After spending 2 months immersing myself in Laravel, I am considering expanding my skills by learning a JavaScript framework. While I have discovered that Laravel comes bundled with Vue.js, there are also options like Angular and React.js which are more po ...

What is the best method for transforming a nested object into an array of objects?

This object contains nested data var arr = [{ "children": [{ "children": [{ "children": [], "Id": 1, "Name": "A", "Image": "http://imgUrl" }], "Id": 2 "Name": "B", ...

The rendering of graphs in FusionCharts is experiencing delays particularly in Internet Explorer, with Chrome performing more efficiently in comparison

I am currently utilizing FusionCharts to generate and display graphs. My requirement is to load over 60 graphs on a single page. Upon testing the page loading in Internet Explorer 11, it is taking approximately 5 minutes. However, when using Google Chrom ...

Entering a string into Angular

Within my function, I trigger the opening of a modal that is populated by a PHP file template. Within this template, there exists a div element containing the value {{msg_text}}. Inside my JavaScript file, I initialize $scope.msg_text so that when the mod ...

Tips for uploading files in filepicker with protractor

https://i.sstatic.net/noq46.png Here's a snippet of HTML code you might find useful: <input type="file" class="fileUploadInput" name="fileUpload" id="fileUploadInput" accept="application/msword,application/pdf,text/plain,application/rtf,applicat ...

Is there a way to dynamically update the text in an HTML element with a randomly generated value using JavaScript?

Currently, I am working on a coding project where I am attempting to create a flip box that reveals the name of a superhero from an array when clicked by a user. The code pen link provided showcases my progress so far: https://codepen.io/zakero/pen/YmGmwK. ...

Error encountered while trying to retrieve Instagram JSON data via request due to an abrupt end of input

I am attempting to retrieve the JSON data from Instagram's URL: . When I enter this URL in my browser, it displays the JSON information. However, I want to be able to access this data using Express so that I can extract any necessary information. co ...

Attempting to retrieve information from my MongoDB database and populate it into a <table> structure on a web page

My objective is to extract data from a MongoDB database and display it in an HTML table. Specifically, I am trying to retrieve information from the hangman database's players collection, which contains fields for name and score. Can anyone help me ide ...

Transferring data from local storage to a PHP server using AJAX

My attempt to transfer data from local storage to PHP using AJAX resulted in an error mentioning 'undefined index data'. chart.php <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="t ...

AngularJS: How can components effectively communicate with each other using best practices?

I've been struggling to figure out how to facilitate communication between components. The primary question that has stumped me is: when should I opt for $watch versus $on ($broadcast/$emit) to establish component communication? I've identified ...