Ryan Prentiss
Ryan Prentiss

Reputation: 1642

Vue 3 Dynamically set selected option of select form element

Using Vue 3, how can I dynamically set the selected option when the data value does not match an available option value?

Condition:

If Florida (FL) is the stored data value for state, and the country is changed from United States (US) to Canada (CA), the State's option value becomes blank. Instead, I would like for the placeholder item to show as the 'selected' option when there is no match.

<template>
    <div>
        <label v-if="data.country === 'US'">
            State
            <select v-model="data.state">
                <option value="" disabled>state</option>
                <option
                    v-for="(state, i) in states"
                    :value="state['code']"
                    :key="i"
                    >{{ state['name'] }}</option
                >
            </select>
        </label>
        <label v-if="data.country === 'CA'">
            Province
            <select v-model="data.state">
                <option value="" disabled>province</option>
                <option
                    v-for="(province, i) in provinces"
                    :value="province['code']"
                    :key="i"
                    >{{ province['name'] }}</option
                >
            </select>
        </label>
    </div>

    <label>
        Country
        <select v-model="data.country">
            <option value="" disabled>country</option>
            <option
                v-for="(country, i) in countries"
                :value="country['code']"
                :key="i"
                >{{ country['name'] }}</option
            >
        </select>
    </label>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import data from '...'
import states from '...'
import provinces from '...'
import countries from '...'

export default defineComponent({
    setup() {
        ...
        return { data, states, provinces, countries }
    },
})
</script>

Upvotes: 3

Views: 12516

Answers (1)

tony19
tony19

Reputation: 138216

You could assign a blank value to the placeholder options:

<option value="" disabled>state</option>
<option value="" disabled>province</option>

And use a watcher on data.country to set data.state to the blank value when the country changes:

import { defineComponent, watch } from 'vue'

export default defineComponent({
  setup() {
    //...
    watch(() => data.country, () => data.state = '')
  },
})

demo

Upvotes: 3

Related Questions