Vue triggering axios on every dropdown selection made

I have a Vue template that currently calls a method (axios call) upon page load, which works well. However, I would like to modify it so that whenever I select an option from the dropdown menu, it will re-call the axios method with the selected option. Specifically, I am looking for a way to pass the selected value of 1, 2, or 3 into the fetchItems method as data = {value} and trigger the axios call based on that selection:

<div class="form-group col-lg-3">
    <label>Choose Item Type</label>
    <select class="form-control" v-model="itemTypes" id="itemTypes">
        <option v-for="itemTypeOption in itemTypeOptions" v-bind:value="itemTypeOption.value">{{ itemTypeOption.name }}</option>
    </select>
</div>

export default {
  data() {
    return {
      itemTypes: [],
      itemTypeOptions: [
        {value: 1, name: "A"},
        {value: 2, name: "B"},
        {value: 3, name: "All"}
      ]
    }
  },
  created() {
    this.fetchItems();
  },
  methods: {
    fetchItems() {
      axios.get('/report/items/data')
      .then(response => {        
        this.rows = response.data
      })
    }
  }
}

Answer №1

To achieve this, you can utilize the @change event in your Vue.js template:


    <template>
    <div class="form-group col-lg-3">
        <label>Select Item Type</label>
        <select class="form-control"
                v-model="selectedItemType"
                id="itemTypes"
                @change="handleSelection">
            <option v-for="typeOption in itemOptions"
                    v-bind:value="typeOption.value">{{ typeOption.name }}</option>
        </select>
    </div>

</template>
<script>
export default {
    data() {
        return {
          selectedItemType: {},
          itemOptions: [
            {value:1, name:"Option A"},
            {value:2, name:"Option B"},
            {value:3, name:"All Options"}
          ]
        }
      },
      created() {
        this.fetchData();
      },
      methods: {
        fetchData(value = '') {
          axios.get('/data/items', {params: {info: value}})
          .then(response => {        
            this.items = response.data
          })
        },
        handleSelection() {
            this.fetchData(selectedItemType.value);
        }
      }
    }
</script>

Answer №2

One of the various methods to achieve this is by including @input="someMethod()" or @change="someMethod()" in your select element. Additionally, you can utilize $event.target.value to access the value directly.

<select class="form-control" v-model="itemTypes" id="itemTypes">
  <option v-for="itemTypeOption in itemTypeOptions" v-bind:value="itemTypeOption.value" @input="fetchItems($event.target.value)">{{ itemTypeOption.name }}</option>
</select>

Here's an example for the fetchItems function:

fetchItems(val = '') {
  axios.get('/report/items/' + val)
  .then(response => {        
    this.rows = response.data
  })
}

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

Retrieve the value with `eventArgs.get_value()` function to obtain the selected text instead of the ID

When I populate a textbox with autocomplete using the code below, it only returns the selected text and not the rowid. Any idea why alert(eventArgs.get_value()) doesn't return the actual ID of the row in SQL? <script language="javascript" type="te ...

Issues with React Router functionality on a live production site are causing complications

I recently created an Amazon-clone UI using create-react-app, but it only displays dummy data. The issue arises after deploying it to Vercel - the routing does not function as expected. When clicking on links, a blank page appears with correct URL paramete ...

Validating the similarity of classes with JQuery

Currently, I am working on creating a quiz game using HTML, CSS, JQuery, and potentially JavaScript. I am looking to implement an if statement to check if a dropped element is placed in the correct div (city). My approach involves utilizing classes to comp ...

What are the steps to create a project template in WebStorm by saving an existing project?

Currently, I am working on my Express.js project in WebStorm 8 and I would like to save it as a project template. Can you please guide me on how to do this using WebStorm? ...

The challenge with linking within Layerslider

Having some trouble with an external link to a specific layerslider slide (html version, NOT wordpress). Here is the webpage in question: After reaching out in the support forum, I was advised to use this javascript: <a href="javascript:void(0);" onc ...

Hide the .prev button on the jQuery slider when it is on the first

Is there a way to hide the .prev button when it is the first one? Also, why does the slider go back to the first slide when the .prev button is clicked at the last slide? How can this issue be resolved? var nextPane = function (e) { e &&am ...

Managing Actions in React-Redux: Understanding the Dispatch Function

While I am delving into the world of React, I stumbled upon an example that looks like this: //index.js const store = createStore(reducer) render( <Provider store={store}> <AddTodo /> </Provider>, document.getElementById(' ...

Replacing npm package dependency

I came across this post: How can I change nested NPM dependency versions? Unfortunately, the solution provided did not work for me. I am attempting to modify a package to utilize a different version of a specific dependency instead of the one it currentl ...

unable to successfully npm install canvas

For my GitHub repository, please visit here This project was actively developed until November of last year, after which I did not commit any changes. Today, I attempted to run the project again but encountered the following error. My current system versi ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...

The THREE.js WebGLRenderer canvas captures the 'click' mouse event

After including the domElement (canvas) from THREE.js WebGLRenderer in my document, I noticed that the 'click' mouse event no longer triggers when clicking on the container element containing the canvas. Is there a method to prevent the canvas f ...

How can I show the post JSON response that was retrieved in ReactJS on the same form component that was used to submit the value?

Thank you for your assistance in advance. I am currently developing a web crawler that will operate in the following steps: The user inputs the seed URL (front-end) The user clicks the submit button (front-end) The seed URL is processed by the backend usi ...

Maximizing the efficiency of rendering components in Ember JS

I have a situation where I need to render thousands of components inside a wrapper component, but currently only around 300 components are being rendered due to performance issues. How can I achieve this without any rendering delays or performance proble ...

Clicking on the ajax tab control in asp.net displays a single rectangular box - how can this be removed?

When using tab control in Ajax, I encountered an issue where a blue rectangle box appeared when clicking or opening the page. How can I remove this unwanted box? ...

assigned to a variable and accessed in a different route

Why does the "res.username" variable return as undefined in the second route even though my user needs to login before accessing any route? router.post('/login', passport.authenticate('local'), function(req, res) { res.username = r ...

Is there a way to selectively display only the first 100 lines using console.log()?

Is there a console.log equivalent of .head() in JavaScript? I need to display only the first 100 lines of a response on my terminal without the top part being cut off due to the entire object being printed. Any suggestions on how to achieve this? ...

Using jQuery, you can utilize the $.when() function with both a single deferred object and an

In my current jquery setup, I am working with two variables. trackFeatures - representing a single ajax request, and artistRequests - an array of ajax requests. I am looking for a way to create a condition that triggers when both trackFeatures and artist ...

Error: Module specifier "react-router-dom" could not be resolved. Relative references should start with either "/", "./", or "../"

I encountered an error message after executing the command npm run preview: Uncaught TypeError: Failed to resolve module specifier "react-router-dom". Relative references must start with either "/", "./", or "../". ...

Choosing items while using the Orthographic camera in Three Js

Currently, I am working on an isometric level and facing issues while trying to select objects within the level. I have tried various solutions from Stackoverflow, such as this one Orthographic camera and selecting objects with raycast. However, none of t ...

Developing a versatile tool to eliminate duplicate items from arrays in JavaScript

Currently, I am in the process of developing a generic utility function that can eliminate duplicates from an array in JavaScript. The snippet below showcases the code where the desired outcome is successfully achieved. My goal is to transform this into ...