Using AXIOS in VueJs to pass response parameters in a v-for loop

I have been developing a VueJs application that makes API calls using AXIOS. In the current setup, users can click a button to display a list of unique manufacturers. Each manufacturer in the list has a button assigned to it, allowing users to view all models under that manufacturer. However, I am still figuring out how to connect functions so that clicking on an object will show a filtered view of models specific to that manufacturer.

Below is the code snippet:

VueJs

    <div v-for="(manufacturerResponse) in manufacturerResponse ">

    <p> <b>Manufacturer ID {{manufacturerResponse.manufacturerId}} </b> 
<b-btn variant="warning" v-on:click="show(); getModels(response.manufactuerId);">View Models</b-btn>

</p>


    </div>

AXIOS - getManufacturer, displaying only unique Manufacturers

    getManufacturers () {
            AXIOS.get(`/url/`)
                .then(response => {
                    console.log(this.manufacturerResponse)

                    this.response = response.data

                    this.manufacturerResponse = []
                    response.data.forEach(item => {

                        if (!this.manufacturerResponse.some(fltr => {
                            return item.manufacturerId == fltr.manufacturerId
                        })) {
                            this.manufacturerResponse.push(item);
                        }
                    });
                })
        },

AXIOS - getModel, showing models under Manufacturer

 getModels () {

            AXIOS.get(`/url/`)
                .then(response => {

                    const id = 0;

                    this.testResponse = response.data.filter (kp6 => kp6.manufacturerId === this.manufacturerResponse[id].manufacturerId );

                    console.log(this.testResponse)

                })

        },

In addition, I have included an example of how the response appears in a simple array:

[
{"id":1,"manufacturerId":1,"model":"Focus"},
{"id":2,"manufacturerId":1,"model":"Transit"},
{"id":3,"manufacturerId":2,"model":"Clio"},
{"id":4,"manufacturerId":3,"model":"Niva"},
{"id":5,"manufacturerId":3,"model":"Yaris"},
]

Answer №1

Within the template, you can find:

v-on:click="show(); getModels(response.manufactuerId);"

However, it is more appropriate to use:

v-on:click="show(); getModels(manufacturerResponse.manufacturerId);" 

as

manufacturerResponse.manufacturerId
currently displays the relevant id, and clicking the button should retrieve models for that specific id.

The getModels() function would receive this parameter as getModels(manufacturerId) and then filter based on that like so:

this.testResponse = response.data.filter(kp6 => kp6.manufacturerId === manufacturerId);

Answer №2

It is important to set up the show() method to accept a parameter of response.manufactuerId

Therefore ...

v-on:click="show(response.manufacturerId);"

Next... within your Vue instance

Ensure that the show method looks similar to this...

show(manufacturerId){
    this.getModels(manufacturerId) // This will invoke the getModels method on the Vue instance and pass in the manufacturerId provided through the click event
}

You may consider skipping the show method altogether and have the click event call getModels directly, passing in the manufacturerId right away.

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

Using `encodeURIComponent` to encode a URL does not function properly when used with a form action

After experimenting with the encodeURI function in conjunction with a form, I discovered an interesting behavior. I used encodeURI to encode a URL. <html> <head> </head> <body> <form id="form"> </form> <button id="bu ...

Is it possible to invoke a TypeScript function that was previously initialized in the HTML file?

I am facing an issue where I want to trigger a function upon pressing a button. The problem arises when I try to call the function that I initialized in the HTML file - the button does not recognize it. Even after using < script> tags, the function ...

Both the complete and success functions are not triggering simultaneously

When I try to use both success and complete together, it seems to not be working properly. If I omit dataType: "jsonp", then the success function works fine, but including it causes only the complete function to work. var reRank = false; function reAss ...

What methods can I use to determine the height of an Angular directive?

For over an hour, I've been trying to accomplish a seemingly simple task: creating an Angular directive that can both retrieve and set the height of the current element. Additionally, this directive should be able to access the browser window in order ...

Creating a Date Computation Tool that Adds Additional Days to a Given Date

I have a challenge where Date 0 represents the start date, Date 1 is the result date after adding a certain number of days (NDays). I am looking for help in JavaScript to calculate Date0 + NDays = Date1. Please assist me as my coding knowledge is quite l ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

Is it possible to delete an item from both the input button and the list?

Asking for help with an issue -> https://stackblitz.com/edit/dropdown-fill-empty-uecsjw?file=src%2Fapp%2Fapp.component.ts Current problem description. The issue I am facing is that after selecting items from a drop-down menu and then deleting them usi ...

Create a loop in Vue.js 3 without the need for a query

Can someone help me understand how to fetch data using a loop in Vue.js version 3 when working with queries? I am trying to retrieve an object based on its id, which is obtained from the URL. However, I seem to be facing some difficulties. Any guidance wou ...

Is there a way to modify the title of an input box, also known as a prompt, using

Is there a method to alter the title of an input box, also known as a prompt, using JavaScript? ...

Leverage React.JS to iterate through arrays and objects, rendering data seamlessly - even within nested objects

Development of Category's Filter component Implementing the rendering of data from a nested array using React Js Although I attempted to render it as seen below, it is not displaying anything The main focus is on the rendering part only var selecte ...

Retrieve JSON object from dropdown menu

I need to retrieve the object name from a dropdown menu when an item is selected. How can I access the object from the event itemSelect? Thank you for your attention. View Dropdown Menu XML code: <core:FragmentDefinition xmlns="sap.m" xmlns:c ...

Ways to properly exit a function

What is the best way to pass the apiKey from the createUser function in User.ts to Test.ts in my specific scenario? User.ts interface User { url: string, name: string, } class User{ async createUser( user: User ):Promise<void> { le ...

Implementing secure Laravel storage with Videojs and Vue.js

I am encountering an issue with accessing privately stored videos from my server using laravel, videojs, and vuejs. Below is the code snippet of my controller method: public function fetchPrivateVideo($video) { $video_path = '/private/courses/e ...

Implementing a JQuery modal with backend coding

I have encountered a problem in my ASP.NET code-behind where I am trying to incorporate a modal popup. Despite my efforts, I have not been able to successfully implement it. Do you have any suggestions on how I should proceed with this process? <scrip ...

What is the best way to ensure buttons remain on the same line in Vue.js?

In a table, I have three buttons that are placed on top of each other when the data in the row is too long and expands the table. My goal is to keep these three buttons in one line regardless of the content length. <td class="text-xs-right"> <d ...

Utilizing the Quasar framework: Triggering a q-dialog from a q-table row will result in the dialog opening for each row within the table

Apologies for any language errors, I am continuously working on improving my English skills. Hi there, I am relatively new to using Vue.js with the Quasar framework. My goal is to open details from a row in a modal (q-dialog). Currently, I have buttons for ...

Is it possible to customize the Menu hover effect in Element Plus and Vue?

Hello everyone, I'm a beginner with Vue, HTML, CSS, and Element Plus. I am trying to customize a Side Bar Menu with my own hover effect, but it doesn't seem to be working. Whenever I change the background color of the el-menu element, the hover e ...

Guide to using AJAX for the GraphHopper Matrix API

I am struggling to send this JSON with the required information because I keep encountering an error during the request. message: "Unsupported content type application/x-www-form-urlencoded; charset=UTF-8" status: "finished" I'm not sure what I&apos ...

Incorporating the Revolution Slider jQuery plugin within a Vue.js environment

Currently, my goal is to transform an html project into a vue application. The initial project utilizes a jquery plugin for Revolution slider by including them through script tags in the body of the html file and then initializing them: <script type= ...

Guide to prompting a browser to download a file using an XHR request

When it comes to downloading files from a server using an XHR request, how can I ensure that the browser initiates the download once the response is received? Additionally, which headers should be included by the server for this process to work seamlessl ...