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

JavaScript fails to function in an HTML file

I am facing an issue where my JavaScript code works perfectly in JSFiddle, but when I copy it into an HTML file, it doesn't function as expected. Despite searching through other related posts, I have been unable to find a solution for this specific pr ...

Navigating through Routing Express and sending data to a template

If I have the following code in my router.get() function, how can I output a template with the data without being able to use res.render()? router.get('/read', function(request, response) { res.send({"result": "Success sent from routes/index ...

What is the process for creating custom command settings for each specific Discord server or guild?

If the server admin writes "!setprefix $" the bot will change its prefix from "!" to "$", but this change will only apply to that specific server. ...

How can you show the default calendar for a specific month and year in a Vue3 datepicker?

I've been utilizing the @vuepic/vue3datepicker component, which automatically shows the days of the current month when integrated in my project: <template> <VueDatePicker v-model="date" inline></VueDatePicker> </templ ...

Collaborative spreadsheet feature within a browser-based software platform

I am using an Angular-based SPA for my web application. My goal is to be able to open an Excel file within the application itself. Currently, I have a menu button or link that is linked to a specific path, for example //192.168.10.10/sharedExcels/myExcel. ...

send a message to all clients using socket.io

I am having trouble figuring out how to broadcast a message from the client or another NodeJS file to all clients. While I was able to send messages to the server successfully, I am not able to reach every other client. Server code: var io = require(&ap ...

How to process and handle a JSON response containing multiple objects using JavaScript

I received a JSON response that looks something like this. { returnCode: 'Success', info: null, result: { payload: '{ "BatchNo":"143123", "Supplier":"Automotive", "ItemNumber":"AP123", ...

Switching jQuery on various sections of a webpage

In my attempt to replicate the functionality of Facebook's Like button, I have encountered a challenge regarding where exactly to click in order to change the button state. When the button is not liked yet, users should be able to click anywhere on t ...

Error: The requested resource, youtube#videoListResponse, is currently unavailable

When attempting to access a YouTube playlist that includes private videos, the bot will encounter an error message. Error: unable to locate resource youtube#videoListResponse Below is the code snippet in question: if (url.match(/^https?:\/\/(w ...

Unable to display nested JSON data from API in Vue.js

Having trouble accessing nested properties from API JSON data. The Vue component I'm working on: var profileComponent = { data : function() { return { isError : false, loading : true, users : null, ...

Ways to Determine if a User Has Closed the Page

How can I detect when a user closes the page without using the back button or typing in a different URL in the address bar? I've attempted to use the following code: $(window).bind('beforeunload', function () { logout(); }); This solutio ...

Nuxt - Guarding Against HTML Injection with Webpack's Plugin

Currently, I am in the process of transitioning a Vue.js App to an Nuxt.js App. Previously, we utilized the favicons-webpack-plugin to create favicons during compilation. These were then embedded into the HTML using html-webpack-plugin. After the migratio ...

main.js vue 3 triggering a pre-create event

I am currently utilizing beforeCreate in the file main.js. Can anyone provide information on how to achieve a similar functionality in Vue 3? let app = Vue.createApp({ template: '<App/>', beforeCreate() { this.$store.commit('initia ...

What is the best way to include a new property to an existing interface and then export the updated interface in Typescript?

Can you provide guidance on creating a new interface - UIInterface that combines SummaryInterface with additional properties? For example: import { SummaryInterface } from 'x-api'; // summaryInterface includes 20+ predefined properties generated ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Enhance the appearance of TreeGrid nodes by customizing the icons according to the data within

Currently, I am working with the MUI DataGridPro component and my goal is to customize the icons of the TreeGrid nodes based on the data. This image illustrates what I hope to achieve: https://i.stack.imgur.com/nMxy9.png Despite consulting the official do ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

Interactive v-card featuring a designated region that is not part of the v-menu

Currently utilizing Vuetify's v-card, I am looking to add click functionality by using the "to" property. Although it works well, there is an issue when incorporating a menu on the top-right side of the card. Clicking on the menu counts as clicking on ...

The pug blend fails to produce the desired output

Recently, I've encountered an issue while working with Pug in a Vue.js application. The task at hand is to create a multi-level menu (with submenus) using the provided data structure: mounted () { this.catalog = [ { title: "Компр ...