3

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>

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.