The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below:

<b-row v-for="demo in demographics" :key="demo.personID">
    ...
    <div class="input-group">
        <b-form-select :id="`guest-${demo.personID}-countryID`"
                        v-model="demo.countryID"
                        v-on:input="changeCountry(demo)"
                        class="mb-2 mr-sm-2 mb-sm-1"
                        :options="countries"
                        value-field="id"
                        text-field="name"
                        :disabled="isOwner(demo.ownerID)"
                        required>
            <template v-slot:first>
                <b-form-select-option :value="null" disabled>-- Select Country --</b-form-select-option>
            </template>
        </b-form-select>
        <b-form-select v-if="demo.stateVisible"
                        :id="`guest-${demo.personID}-stateID`"
                        v-model="demo.stateID"
                        class="mb-2 mr-sm-0 mb-sm-1"
                        :options="states"
                        value-field="id"
                        text-field="name"
                        :disabled="isOwner(demo.ownerID)"
                        required>
            <template v-slot:first>
                <b-form-select-option :value="null">-- Select State --</b-form-select-option>
            </template>
        </b-form-select>
    </div>
    ...
</b-row>

// function to manage state visibility
changeCountry(demo: TourDemographicsModel) {
    if (demo.countryID && demo.countryID == 1) {
        demo.stateVisible = true;
    } else {
        demo.stateVisible = false;
    }
}

// model interface
export interface TourDemographicsModel {
    // ...
    countryID?: number
    stateID?: number
    stateVisible: boolean
}

The current setup successfully hides or shows the state dropdown based on the selected country when the page loads, but it doesn't dynamically adjust visibility when the country selection is changed. Any suggestions on how to address this issue?

Just for your information - I am working with Vue version 2.6 and utilizing TypeScript.

Answer №1

The v-model feature in Vue.js utilizes the input event behind the scenes, essentially translating to v-on:input="modelValue = $event.target.value" :value="modelValue". This setup means that your input handler may not always execute after the implicit v-model handler, leading to a scenario where the demo object has not been updated by the time changeCountry is triggered.

A more effective approach is to create a method based on the demo object:

methods:{
    isStateVisible(countryId : number | undefined) : boolean{
        return (countryId && countryId == 1);
    }
}

You can now eliminate v-on:input="changeCountry(demo)" and replace it with:

<b-form-select v-if="isStateVisible(demo.countryID)" //take note of the new v-if condition
                    :id="`guest-${demo.personID}-stateID`"
                    v-model="demo.stateID"
                    class="mb-2 mr-sm-0 mb-sm-1"
                    :options="states"
                    value-field="id"
                    text-field="name"
                    :disabled="isOwner(demo.ownerID)"
                    required>

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

What materials are required in order to receive messages and information through my Contact page?

Currently, I am pondering the optimal method for gathering information from my Contact page. I have already created a form; however, I'm unsure how to send the gathered data to myself since I am relatively new to Web development. Angular is the framew ...

How can I access data from a function that is executed within a method in Vue.js?

When working with vuejs and JS scopes, passing a value to a style property inside data can be tricky. The issue arises when trying to access this.data.property: Vue.component ('loader-component', { template: '#loader-template', mo ...

Exploring methods for testing React components with TypeScript's props

I am currently tackling a react-typescript project and I am looking to conduct testing on props passed to a react component using react-testing library. Here, we have the SharedDashboardUiLatestValueWidget.tsx component: export interface SharedDashboardU ...

Leveraging Axios for parsing JSON data that consists of values without corresponding keys

Struggling to divide this JSON data into two separate arrays {"2022-08-11":11561.71,"2022-08-12":11396.5433,"2022-08-13":10875.3483,"2022-08-14":10036.1867,"2022-08-15":10307.895,"2022-08-16":1035 ...

Building a search form using Vue.js with query parameters

Incorporating Vue.js 2.6 with the vue-router component has been quite a journey for me. My search form setup looks like this: <form class="search-form" @submit.prevent="search"> <div class="form-group"> <input type="text" class= ...

Struggling to comprehend the intricacies of these generic declarations, particularly when it comes to Type Argument Lists

I'm currently reviewing the code snippet from the TypeScript definitions of fastify. I am struggling to understand these definitions. Although I am familiar with angle brackets used for generics, most TypeScript tutorials focus on simple types like Ar ...

Leveraging constructors for injecting dependencies in Angular is a key practice for enhancing modularity and maintainability

After reviewing the Angular Official documents and various blogs, I noticed that there are two different syntaxes for Dependency Injection (DI) when used within the constructor. Sometimes this is utilized, while other times it is not. This leads to the que ...

Steps for clicking on the center of a leaflet map with protractor

I'm currently facing an issue where I am attempting to click on the center of a map located in the second column of the webpage, which has an offset. However, I am encountering a problem where the cursor always points to the center of the page instead ...

Is it Possible for Angular Layout Components to Render Content Correctly even with Deeply Nested ng-container Elements?

Within my Angular application, I have designed a layout component featuring two columns using CSS. Within this setup, placeholders for the aside and main content are defined utilizing ng-content. The data for both the aside and main sections is fetched fr ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

What does the "Undefined" group label mean in Vue-Multiselect?

I recently started learning Vue and have revamped this code based on information from different tutorials. However, I am encountering an issue with the group name showing as "Undefined" here. .html: <multiselect v-model="value" :options="op ...

In Angular, make a call to a second API if the first API call times out after a specified period

In the event that my API does not return data within 5 seconds, I need to call a different one. Attempted implementation: this.service.returnData1(param1, param2) .pipe(timeout(5000), finalize(() => this.callSecondApi())) .subscribe( data => { ...

The http post request is functioning properly in postman, but it is not working within the ionic app

I am currently developing an app in ionic v3 within visual studio (Tools for Apache Cordova). On one of the screens in my app, I gather user information and send it to an API. However, I'm encountering an issue with the HTTP POST request that I'm ...

Combining Axios with repeated promises

I am facing an issue with a loop in my GET request on the axis, and I cannot figure out why. const [ state, setState ] = useState<any[]>([]); ids.forEach((id) => { getData(id) .then((smth: Map<string, any>[]) => getNeededData ...

In TypeScript, enhancing an interface with additional properties

Currently, I am working on an Angular project and have developed this interface to display some data: export interface UserData { name: string, vorname: string, strasse: string, plz: string, ort: string, handynummer: string, telefonnummer: s ...

Is it possible to set up a universal type definition in TypeScript version 2 and above?

I have a collection of straightforward .ts files, not part of any projects but standalone .ts scripts. They implement certain node.js features. Both TypeScript and node type definitions are set up through the following commands: npm install -g typescript ...

The process of ordering awaits using an asynchronous method

async fetchAndStoreRecords(): Promise<Records[]> { this.subRecords = await this.afs.collection<Records>('records') .valueChanges() .subscribe((data: Records[]) => { console.log('log before data ...

Ways to implement jsdoc on vue3 props without utilizing typescript?

const props = defineProps({ items: { /** @type {{new(): Color[] }} */ type: Array, required: true, }, selectedColor: { type: Object, required: true, }, composable: { type: Function, required: true } }) We do not use T ...

The Vue transition classes fail to properly function when entering and exiting

I have created a codepen featuring a simple flip card. The code works perfectly in Codepen, but when I integrate it into my Vue project generated with vue cli, there seems to be an issue. While clicking on a card displays its back, the transition effect th ...