我的 Vue 应用程序中有一个选择元素,其中包含根据用户在应用程序中设置的其他选项有条件地显示或删除的选项,如下所示:
<select id='animal' v-model='values.animal.selected'>
<option value='cat' v-if='legs == 4'>Cat</option>
<option value='dog' v-if='legs == 4'>Dog</option>
<option value='bird' v-if='legs == 2 && wings == 2'>Bird</option>
<option value='snake' v-if='!legs'>Snake</option>
</select>
通过此设置,当用户更改腿的数量
时,选项会相应地出现和消失。然而,当选定的选项应更改为可用选项之一时,它通常仍然是隐藏选项之一。当选项更改时,特别是第一个选项,是否可以更改选择元素的选定值?
最佳答案
您需要检查过滤值何时发生变化,然后用第一个与过滤条件匹配的值更新所选值。
试试这个代码
<template>
<div id="app">
<p>
filter options
</p>
<input type="number" v-model="amountLegs"/>
<br>
<select id="animal" v-model="selectedAnimal">
<option
v-for="(animal, index) in filteredArray"
:key="index"
:value="animal.val"
>
{{ animal.label }}
</option>
</select>
<br>
<p>selected value: {{ selectedAnimal }}</p>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
amountLegs: 0,
selectedAnimal: 'snake',
animals: [
{
val: 'cat',
label: 'Cat',
legs: 4
},
{
val: 'dog',
label: 'Dog',
legs: 4
},
{
val: 'bird',
label: 'Bird',
legs: 2
},
{
val: 'snake',
label: 'Snake',
legs: 0,
},
],
};
},
computed: {
filteredArray() {
return this.animals.filter(x => x.legs === this.amountLegs);
},
},
methods: {
onChangeAmountLegs() {
const selectedAnimal = this.animals.find(x => x.val === this.selectedAnimal);
const legs = this.amountLegs;
if (selectedAnimal) {
if (selectedAnimal.legs !== legs) {
const animal = this.animals.find(x => x.legs === legs);
this.selectedAnimal = animal ? animal.val : null;
}
} else {
const animal = this.animals.find(x => x.legs === legs);
this.selectedAnimal = animal ? animal.val : null;
}
},
},
watch: {
amountLegs(val) {
if (val) {
this.amountLegs = typeof val === 'string' ? parseInt(val) : val;
this.onChangeAmountLegs();
}
}
}
};
</script>
关于javascript - 在 Vue.js 中,当选项有条件显示和隐藏时,如何确保选择元素连续选择第一个选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53662143/