Vue 3 动态设置 select 表单元素的 selected 选项

Vue 3 Dynamically set selected option of select form element

使用 Vue 3,当数据值与可用选项值不匹配时,如何动态设置 selected 选项?

条件:

如果佛罗里达州 (FL) 是州的存储数据值,并且国家从美国 (US) 更改为加拿大 (CA),则州的选项值变为空白。相反,我希望占位符项在没有匹配项时显示为 'selected' 选项。

<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>

您可以将空值分配给占位符 options:

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

并在 data.country 上使用 watcherdata.state 设置为国家更改时的空白值:

import { defineComponent, watch } from 'vue'

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

demo