javascript - 在 Vue.js 中,当选项有条件显示和隐藏时,如何确保选择元素连续选择第一个选项?

标签 javascript vue.js vuejs2

我的 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/

相关文章:

javascript - jQuery AJAX 回调

javascript - jQuery:如何在尚未添加到 DOM 的元素上调用 jQuery 插件函数?

javascript - 如何将现代版本的 Vue (Vue CLI3) 与 Electron 结合使用?

javascript - 移动到其他数组时 Vue 保持事件组件

javascript - Vuejs 将 props 从对象传递到动态组件

javascript - vue.js - v-html 替代方案

javascript - 无法使用post请求nodejs重定向

javascript - Fancybox 没有导航按钮,但有画廊作品

javascript - 如何向模板外部的组件添加 Prop

javascript - VueJS 中的下拉菜单(事件菜单的切换)