Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hardcode them, but I don't know how to pass the id into the async mounted axios function "api/sd/model/get", id)

Here is my template:

   
  <main class="home-page">
   
       <select v-model="selectedMark">
        <option v-for="model in items" :key="model.id">{{ model.name.value  }}</option>
      </select><br><br>

        <select v-model="selectedModel">
        <option v-for="make in info" :key="make.id" >{{ make.name.value }}</option>
      </select><br><br>

      
        <button type="submit" class="conectButton">Połącz</button>
      <div class="titleCarMain"><p class="titleCar">{{selectedMark}}</p><p class="titleComponent">{{selectedModel}}</p></div>
    
     
  
     </main>

This is the script:

import axios from 'axios';

export default {
  name: "App",
  data() {
      return { 
      
      info: null,
      items: [],
      selectedMark: null,
      selectedModel: null,

      };
  },
  
  async mounted() {
   axios
     .get("http://local/api/sd/make/get")
     .then(response => { this.items = response.data.data.items });
    

    const id = { id: this.selectedMark }  //doesn't work
     
    await axios
     .post("http://local/api/sd/model/get", id) //doesn't work 
     .then(response => { this.info = response.data.data.items });

   },
   
  
};

Can anyone help this newbie out? It would be amazing if you could also explain why your solution works for better understanding. Thanks in advance!

Answer №1

The current issue is that the component isn't functioning correctly because when it is mounted, selectedMark is initially set to null. In order to successfully fetch data from the "http://local/api/sd/model/ge" endpoint within the mounted hook, you need to somehow define selectedMark - for example, by using the id of the first item.

async mounted() {
  this.items = await axios
   .get("http://local/api/sd/make/get")
   .then(response => response.data.data.items);
  
  if (this.items.length) {
    this.selectedMark = this.items[0].id;
    const id = { id: this.selectedMark };
    await axios
      .post("http://local/api/sd/model/get", id)
      .then(response => { this.info = response.data.data.items });
    this.selectedModel = this.info.length ? this.info[0].id : null;
  }
},

If you want to fetch new data each time a different item is selected, you'll need to create a function that is triggered on the change event.

<select v-model="selectedMark" @change="onchange">
    <option v-for="model in items" :key="model.id" :value="model.id">
      {{ model.name.value }}
    </option>
</select>

async onchange() {
  this.info = await axios
    .post("http://local/api/sd/model/get", { id: this.selectedMark })
    .then(response => { response.data.data.items });
  this.selectedModel = this.info.length ? this.info[0].id : null;
}

Don't forget to add the :value attribute to the option tags

Here's a working example BUT utilizing the JSON placeholder FREE REST API (for demonstration purposes)

Answer №2

To handle the selection change event, you can utilize the @change event and implement it within the Methods hook as shown in the example below.

<template>
  <main class="home-page">   
    <select v-model="selectedMark" @change="getInfo(selectedMark)">
        <option v-for="model in items" :key="model.id">{{ model.name.value  }}</option>
    </select>
    <br><br>
    <select v-model="selectedModel">
        <option v-for="make in info" :key="make.id" >{{ make.name.value }}</option>
    </select>
    <br><br>
    <button type="submit" class="conectButton">Connect</button>
    <div class="titleCarMain"><p class="titleCar">{{selectedMark}}</p><p class="titleComponent">{{selectedModel}}</p></div>
 </main>
</template>

<script>

import axios from 'axios';

export default {
  name: "App",
  data() {
      return {
        info: null,
        items: [],
        selectedMark: null,
        selectedModel: null,
      };
  },
  created() {
    this.getItems()
  },
  methods: {
    getItems() {
        axios
        .get("http://local/api/sd/make/get")
        .then(response => { this.items = response.data.data.items });
    },
    getInfo(selectedMark) {
        await axios
        .post("http://local/api/sd/model/get", selectedMark) //does not work 
        .then(response => { this.info = response.data.data.items });
    },
  }
};

 

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

Exploring the functionality of placeholders within jQuery

I am trying to create a customizable text template where I can insert placeholders and then fill those placeholders with data to use on my page. For example: var template = '<div class="persons">'; template += '<p> <span clas ...

Advantages of incorporating lazy loading in a Vue Single Page Application:

What level of realistic benefit can be expected from lazy loading in a Vue application using Vue-router, Vuex, and many components to improve initial load times in an SPA? In comparison to minifying and bundling code (in this case, with gulp), do the perf ...

Creating an infinite scroll with a gradient background: a step-by-step guide

I am currently working on a project to develop an infinite scrolling webpage with a dynamic gradient background that changes based on the user's scroll position. While researching, I came across some code for infinite scrolling using time and date. I ...

Generating a component and rendering it according to the dynamic route parameters using mapStateToProps and reselect techniques

I have set up a global app container to store data for different rooms, with a sub-container called roomDetails that utilizes a reselect selector to pick a room from the global state based on ownProps.params.slug. This process is accomplished through mapSt ...

Is it possible to simultaneously run multiple functions with event listeners on a canvas?

I'm attempting to create a canvas function that displays the real-time mouse cursor location within the canvas and, upon clicking, should draw a circle. I came across this code snippet that reveals the x and y coordinates of the mouse: document.addEve ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

Ways to create a class method to increase a counter?

Can someone help me figure out how to create a custom function or class from the code below? I want to be able to import this module in order to easily increment a count whenever an event occurs in my application. I'm tired of having to manually inpu ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

How can the button effect be disabled in Vue Material for md-button?

Is there any documentation available for disabling the effect from md-button in Vue Material? Thank you ...

Tips for correctly mentioning a user while using message.channel.send in discord.js

Looking for guidance on tagging a user properly using message.channel.send in discord.js? Here's the code I'm currently working with: function replaceAll(str, find, replacer) { return str.replace(new RegExp(find, 'g'), replacer) ...

Place the script tags within the window.load function inside the head section

<head> <script type="text/javascript"> $(window).load(function() { // <script src="js/external.js"></script> // }); </script> </head> Is it possible to insert a script tag(< script src="js/exte ...

What are some ways to enhance the speed of my canvas animations?

My code generates imagedata and places it in a canvas. However, when I expand the window size, the rendering slows down significantly. Is there a way to optimize this for smooth operation in fullscreen mode, even though it might seem naive? What would be ...

How to use Ionic 3 to automatically scroll ion-scroll content all the way to the bottom

My ion-scroll component is experiencing some challenges <ion-scroll scrollY="true" style="height: 52vh;"> {{ text }} </ion-scroll> The content inside the ion-scroll keeps expanding, exceeding the designated height. Users can manually scroll ...

Clicking on an embedded YouTube video will automatically redirect you to the video's

Hey there, I've added an embedded video to my website and I'm wondering if it's possible to redirect users to a new site when they click the play button? Thanks in advance! ...

What steps can be taken to troubleshoot and resolve this specific TypeScript compilation error, as well as similar errors that may

I am struggling with this TypeScript code that contains comments and seems a bit messy: function getPlacesToStopExchange(): { our: { i: number; val: number; }[]; enemy: { i: number; val: number; }[]; //[party in 'our' | 'enemy' ]: ...

The table is unable to properly display the array data

My code includes an AJAX function that sends a GET request to an API and receives data in the format shown below: { "firstname": "John", "lastname": "Doe", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6 ...

How can I modify the query parameter value in vue-router?

router.push({ path: 'register', query: { plan: 'private' } }) will create a URI like: http://localhost:3000/#/register?plan=private&plan=public in case the query parameter with key plan and value public already exists in $currentR ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...