Guide to triggering an API call upon changing the value in a Vue Multiselect component

Is there a way to trigger an API call when the value changes in a Vue Multiselect component? I want to update the value in the multiselect, make an API call, and display the result in the console. Below is my code snippet.

<template>
    <div>

        <multiselect v-model="value" placeholder="Select Your Currency" label="title" track-by="title" :options="options" :option-height="10"  :show-labels="false">
            <template slot="singleLabel" slot-scope="props"><img class="option__image"  :src="props.option.img" alt="No Man’s Sky"><span class="option__desc"><span class="option__title">{{ props.option.title }}</span></span></template>
            <template slot="option" slot-scope="props"><img class="option__image" :src="props.option.img" alt="No Man’s Sky">
                <div class="option__desc"><span class="option__title" :id="props.option.id">{{ props.option.title }}</span><span class="option__small">{{ props.option.desc }}</span></div>
            </template>
        </multiselect>

         </div>
         </template>

          <script>
    import Vue from 'vue';
    import Multiselect from 'vue-multiselect'
    Vue.component('multiselect', Multiselect);

    export default {
        props: ['options'],
        components: {
            Multiselect
        },
        data () {
            return {
                value: { title: 'Bitcoin', img: 'https://coinnik.com/uploads/crypto-logos/06fa2ab3d5a0f1d60e7d236aeccd6c6a.png' },

            }
        },
        methods: {

           }
        }
      </script>

app.js

    methods: {
        stepChanged(step) {
            this.currentstep = step;
        },
        apiCalc(){
            let self = this;

            axios.get('/ajax-calculation?includes=direction,direction.receiveCurrency&send_currency=2').then((response) => {
                self.calcApi = response.data;
                console.log('api:',self.calcApi.currency_id);
                // self.calcApi.currency_id;


            })
        }
    },
    components:{
        'multiselect': Multiselect
    },

    created() {
        this.apiCalc();
        },
      });

html

     <div class="col-md-12 mb-2">
<multiselect                                                                        :options="[                                                                                 { title: 'Tether', img: 'https://coinnik.com/uploads/crypto-logos/006fe133d48ea7cd45cf8ccb8cb7ec42.png' },
{ title: 'value', img: 'https://coinnik.com/uploads/crypto-logos/006fe133d48ea7cd45cf8ccb8cb7ec42.png' }]">
</multiselect>
</div>

How can I define a method that triggers an API call and displays results in the console when an item is changed?

Answer №1

Utilize the deep watch feature to monitor changes in the value variable.

watch: {
  'value': {
    handler: function (after, before) {
      this.apiCalc();
    },
    deep: true
  },

},

Answer №2

Alright, to begin with, you can utilize the @input event to detect when a selection has been made, as demonstrated in this example:

<multiselect v-model="value" :options="options" @input="callApi" multiple></multiselect>

In the function callApi, you can inspect the current value.

callApi() {
    console.log(this.value);
}

The variable this.value will contain an array of the selected items. These can then be sent to your API for further processing. You can find the complete code sample on CodePen: https://codepen.io/cfjedimaster/pen/gOOjjrb?editors=1111

Answer №3

If you haven't already, give the @select event a shot. Vue Multiselect offers various events to explore, so take a look at the documentation over here:

Here's how you can implement it:

<multiselect v-model="value" :options="options" @select="actionToPerform" multiple></multiselect>

Make sure to define this in your methods section. I'm also using Vue Multiselect, so feel free to reach out if you need any assistance with it.

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

Leveraging AJAX for transmitting form information to a php script without relying on jQuery

I want to explore AJAX by implementing a basic form data submission to a php script and database. For educational purposes, I've reached a standstill after hitting the "Create Profile" button with no action. Could someone spot any syntax or structural ...

Making numerous changes to a single field in mongoDB can result in the error message: "Attempting to edit the path 'X' will generate a conflict at 'X'."

Looking to streamline my update operation: private async handleModifiedCategoryImages(data: ModifiedFilesEventData) { this.categoryModel .findByIdAndUpdate(data.resourceId, { $pullAll: { images: data.removedFiles || [] } ...

Innovative and interactive animated data display

I've taken inspiration from an example and expanded the code to achieve the following: Dynamic height adjustment Accessibility without JavaScript enabled Is this implementation correct? Can it be expected to function properly on most browsers? You ...

Unable to pass parameters using ViewBag in jQuery within a partial view

Currently, I am in the process of building an MVC3 application with razor syntax. My focus right now is on developing the partial class that will be responsible for handling comments. This is a snippet of my code: <script src="../../Scripts/jquery.js" ...

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

Is it possible to return a promise after utilizing .then() in AngularJS?

As someone who is still getting the hang of Angular and promises, I want to make sure I'm on the right track. Right now, my data layer service uses Restangular to fetch data and returns a promise. Here's how it looks... dataStore.getUsers = fun ...

No entries found in the Nuxt/content module's array

<template> <div> <input v-model="searchQuery" type="search" autocomplete="off" placeholder="Search Articles" /> <ul v-if="articles.length"> ...

The previous method of using `vue/compiler-sfc ::v-deep` as a combinator has been phased out. Instead, opt for the new syntax `:deep(<

When developing with Nuxt 2, I am encountering numerous [@vue/compiler-sfc] ::v-deep usage as a combinator has been deprecated. Use :deep(<inner-selector>) instead. errors when running npm run dev. After attempting to resolve the issue by changing a ...

Suspend Coontact-Host Upload of Documents

Is there a way to pause or resume uploading, or resume a broken upload using PHP, JavaScript, or jQuery without having to rely on Java, Flash, or C-type programming? Perhaps utilizing PHP socket functions? ...

Enhance the php query limit using javascript when loading additional content

Hey there, currently working on implementing a reverse infinite scroll feature for a private messaging module. Everything seems to be functioning well, except for one issue I'm facing - struggling to update the query limit. I set the maximum and lim ...

Developing interactive checkboxes for individual rows through React.js

Within a form, I have rows containing two inputs each. Upon clicking "add", a new row is created. For the second row onwards, by clicking "add" a checkbox labeled 1 should be added to indicate dependency on the previous row. In addition, for the third row, ...

Looking for the final entry in a table using AngularJS

Hey everyone, I'm dealing with a table row situation here <tbody> <tr *ngFor="let data of List | paginate : { itemsPerPage: 10, currentPage: p }; let i = index"> <td>{{ d ...

Learn how to properly convert a string into a valid URL using the Next JS router when pushing pages

I'm dealing with a string that looks like this: /dashboard/products/:id. My goal is to utilize Next Js's router to navigate to that URL and replace the placeholder :id with an actual id. Here's the code I've written: {products.map(prod ...

Is there a way to utilize two separate buttons in VueJS in order to reverse and remove a message at the same time

Attempting to achieve the same outcome by inverting and deleting a message using two separate buttons for this exercise. I followed a VueJS tutorial but encountered an issue where the console displayed: this.text is not a function I have tried various ...

Having an issue with Jquery selector where the text does not match

HTML Code <select id="myDropdown"> <option selected="selected" value="0">default</option> <option value="1">bananas</option> <option value="2">pears</option> </select> Javascript Function setDr ...

"Declare the Status, Refresh the Page, and Specify the Web

After refreshing the page, I am facing an issue where the text corresponding to the current URL is not being displayed. My application consists of a Main component that renders a MiniDrawer component containing a NavLink, followed by routing with the Route ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

How can Mbox content be loaded dynamically according to the selected option in a dropdown menu, instead of loading it when

I am looking to enhance my asp.net page by adding a new MBox that will be triggered based on the dropdown selected value. Unlike other MBoxes on the page that load on page load, I want this new MBox to dynamically pass custom parameters to T&T when a val ...

Struggling to place buttons below each row in a Bootstrap DataTable, unfortunately, they are only appearing under a specific column rather than the entire row

I have developed a system for managing event expenses that includes an option for multiple installments of a single payment for each event. My goal is to display these installments when a user hovers over an event in the table, with each row representing a ...

A pattern matching formula to eliminate specific characters from the beginning to the end of a string

I am facing an issue with extracting content from a given string: var string = "From: Sarah<br /> Sent: 10 May 2021 09:45:20</br /> To: Alice<br /> Subject: Meeting Reminder<br /><br /> Hi Alice, <br /> Here is a ...