Using Bootstrap Vue to select and send the previous value

Here is the code I am using for a select input in Vue Bootstrap:

<b-form-select v-model="selectedgroup" class="mb-3"  @change="searchSubGroup()">
    <option :value="null">Select a group</option>
    <option v-for="group in groupItem" :value="group.id">
        {{group.nome}}
    </option>
</b-form-select>  

Whenever the searchSubGroup() method is triggered by the @change event, it passes the previous value of selectedgroup. For example, if I first select an option with value = 1, the method will be called with selectedgroup as null, then if I select another option with value = 2, the method will be called with selectedgroup as 1.

searchSubGroup(){ 
  this.axios.get("http://chart.solutions/public/api/produto/subgroup/search/" + this.selectedgroup + "/").then(response => {
        if (response.data.erro) {
            //console.log("subgroup doesnt exist")
        }else{
            this.subGroupItem = response.data;
        }
    })
} 

Answer №1

To enhance your code, make sure to call the searchSubGroup method without using parentheses, so that the newly selected value is automatically passed to the function.

<b-form-select v-model="selectedgroup" class="mb-3"  @change="searchSubGroup">
    <option :value="null">Select a group</option>
    <option v-for="group in groupItem" :value="group.id">
        {{group.nome}}
    </option>
</b-form-select>

In your method, ensure you follow these steps:

searchSubGroup(value){ 
  this.axios.get("http://chart.solutions/public/api/produto/subgroup/search/" + value + "/").then(response => {
        if (response.data.erro) {
            //console.log("subgroup doesnt exist")
        }else{
            this.subGroupItem = response.data;
        }
    })
} 

Answer №2

To fix the issue, make sure you exclude the parentheses from the @change call like this:

@change="searchSubGroup"

If you keep the parentheses in place, the function will be triggered during the component build process when "selectedgroup" is still undefined, resulting in a call with null.

The problem arises because v-model relies on @change, causing the event to fire twice. The selectedGroup method is executed before the change method updates the v-model data, leading to the use of the "old value."

While another answer provides a solution to work around the problem, it lacks an explanation for why this behavior occurs.

Here's an alternative approach:

  1. Remove the @change call from b-form-select
  2. Add a "watched" property

    watch: {
         selectedgroup(value) {
              this.searchSubGroup();
              //OR you could remove the method and just call axios here
         })
    }

Answer №3

You might want to consider using @input instead of the @change event because @input="searchSubGroup" will give you the currently selected item.

new Vue({
  el: '#app',

  data() {
    return {
      selected: null,
      options: [{
          value: null,
          text: 'Please select an item'
        },
        {
          value: 'a',
          text: 'Option a'
        },
        {
          value: 'b',
          text: 'Default Selected Option b'
        },
        {
          value: 'c',
          text: 'Option c'
        },
        {
          value: 'd',
          text: 'This one is disabled',
          disabled: true
        },
        {
          value: 'e',
          text: 'Option e'
        },
        {
          value: 'f',
          text: 'Option f'
        }
      ]
    }
  },
  methods: {
    choose() {
      console.log(this.selected)
    }
  }

});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  ...
  // Add necessary scripts and links
  ...

</head>

<body>

  <div id="app">

    <b-form-select v-model="selected" :options="options" class="mb-3" @input="choose">
    </b-form-select>
    <div>Selected: <strong>{{ selected }}</strong></div>
  </div>

  <script src="script.js"></script>
</body>

</html>

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

Encountering an Invalid Form Body error (DiscordAPIError[50035]) while attempting to register my commands on Discord

After following the discord.js guide to create a suggest command using a basic command handler, I encountered an error when deploying my commands. Despite being new to DiscordJS, I have attempted to troubleshoot by adjusting my embeds. DiscordAPIError ...

How to retrieve the column names of a table using Web SQL?

Working on extracting column lists from Web SQL (Chrome's local database). One approach is to gather information from sqlite_master. SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "'+name+'"; As an example, here is a sam ...

What is the best way to incorporate a webpack bundle into another bundle?

Greetings! I am currently in the process of developing a React application with server-side rendering. The server and client segments are both written in TypeScript and transpiled separately to ensure smooth functionality. To provide you with a clearer pic ...

I'm curious about using NextJS to fetch an API with a specific router ID. Can anyone provide guidance on how to achieve this and then render the data as HTML?

Greetings! I am currently coding in NextJS and working on a user page that fetches user-specific information from an API. My goal is to extract the ID query from the URL and use it to make an API request. The API endpoint follows this structure: /Users/{i ...

The Jqueryui image link is not displaying the image despite no error being reported

Can anyone help me figure out what I'm missing? I'm currently working with ASP.NET MVC 5 and have downloaded the JqueryUI combined via Nuget package. Despite no error references for css/js files, the close button is still not showing in the ima ...

Sending data from a PHP function to an AJAX call in the form of an associative array using json_encode() does not

Greetings, this is my first post so please forgive me if I miss anything or fail to explain clearly. All the code below is within the same PHP file. Here is my AJAX call: $.ajax( { type: "POST", url: window.location.href, data: {func: 'g ...

I attempted to access data from the phpmyadmin database, but the browser is displaying an error message stating "cannot get/employee", while there are no errors showing in the command prompt

const { json } = require('express/lib/response'); const mysql=require ('mysql'); const express=require('express'); var app=express(); const bodyparser=require('body-parser'); app.use(bodyparser.json()); var mysq ...

Capturing user input upon submission of a form?

When the user submits my form, I want to retrieve an input value: <input type="text" id="name"> I am aware that I can use form input bindings to update values to a variable, but is there a way to do this only upon submission? Currently, I have: &l ...

What is the best way to apply a class to a button in Angular when clicking on

Creating a simple directive with two buttons. Able to detect click events on the buttons, but now looking to add a custom class upon clicking. There is a predefined class: .red { background-color: red; } The goal is to dynamically apply this class whe ...

Having difficulty displaying TIFF images and incorporating them into a Fabric Object

I have gone through the tutorials available at: and also familiarized myself with the Fabric Objects documentation. While I was successful in loading JPG and PNG images onto the canvas, my current project requires me to load TIFF images and apply filters ...

Utilizing Vue 3 props validation in conjunction with the power of Typescript

Looking to customize a Link component using Nuxt, Typescript, and the composition-api. The prop target can accept specific values as outlined below. I'm curious if using a custom validator function to check prop types at runtime adds value when compar ...

Delay the execution of Javascript code for one hour daily over the course of a month

Updated Question: Despite the larger issue, can someone explain why the sleep function in the code below doesn't provide a one-hour pause in execution? Understanding this would be greatly appreciated. I am trying to trigger a JavaScript function that ...

<dt> and <dd> have not been added after the previous element

I can't seem to figure out why the dt and dd elements are not being added to the dl I created. Here's my initial attempt: // Dictionary list var words = [ { term: "Procrastination", definition: "Pathological tendency to s ...

struggling with managing an array of Vue3 refs

Having an issue with handling vue3 refs, specifically when retrieving data from Firestore. When logging the [documents], everything seems to work fine. However, I run into errors when trying to access values from an array within a document. For example, ...

Navigating through external JSON data in a Node.js and Express application, and rendering the data using Jade

After going through various examples and solutions in related questions on StackExchange in an attempt to solve my issue, I have decided to post my question. My ultimate goal is to access complex JSON data via an API and REST. I intend to import this data ...

What is the best way to transform an Observable array containing objects into an Observable that emits the data contained within those objects?

Encountering an error: Error: Type 'Observable<Country[]>' is not assignable to type 'Observable'. Type 'Country[]' is missing properties like name, tld, alpha2Code, alpha3Code and more.ts(2322 The issue might be due ...

Executing a function a specific number of times in Jquery

I have a query regarding JQuery related to randomly placing divs on a webpage. The issue I'm facing is that it currently does this indefinitely. Is there a way to make it run for a specific duration and then stop? $(document).ready(function () { ...

The system seems to be having trouble locating the password property, as it is returning a value of

I'm currently working on a database project using MongoDB and Node.js. I'm trying to update a specific field, but unfortunately I keep getting an error. The model I am working with is called "ListaSalas": router.post('/updatesala', fun ...

The gridview fails to update when I attempt to click on the update button

Here is my updated code snippet for the GridView After clicking on the update button, the gridview is not being updated and instead reverting back to its previous value. However, the delete option is working correctly. Id = ( ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...