VUE3动态设置select表单元素的select选项

ev7lccsx  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(1093)

使用vue 3,如何动态设置 selected 数据值与可用选项值不匹配时的选项?
条件:
如果佛罗里达州(fl)是该州存储的数据值,并且该州从美国(us)更改为加拿大(ca),则该州的选项值将变为空白。相反,我希望占位符项在没有匹配项时显示为“选定”选项。

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

li9yvcax1#

可以为占位符指定空白值 option s:

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

并在屏幕上使用观察者 data.country 设置 data.state 当国家改变时的空白值:

import { defineComponent, watch } from 'vue'

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

演示

相关问题