IT이야기

vuejs 2에서 선택 입력 옵션을 동적으로 변경

cyworld 2022. 5. 18. 22:00
반응형

vuejs 2에서 선택 입력 옵션을 동적으로 변경

v-모델 선택 드롭다운에서 옵션을 동적으로 변경하는 방법?

나는 2개의 선택 입력이 있는데 하나는 다른 입력에 따라 달라져야 한다.

예를 들어, "과일"을 선택하면 과일이 표시되고, "채소"를 선택하면 야채가 표시된다.

나는 Vuejs를 사용하지 않지만, 설명서를 본 후에:

var TypesArr = {
                Fruit: [{ text: 'Apple', value: 'Apple' }, { text: 'Orange', value: 'Orange' }, { text: 'Mango', value: 'Mango' }],
                Meat:  [{ text: 'Steak', value: 'Steak' }, { text: 'Pork', value: 'Pork' }]
               }


var selectTwo = new Vue({
    el: '#select2',
    data: {
           selected: TypesArr['Fruit'][0],
           options: TypesArr['Fruit']
       },
       methods: {
         update: function (value)
         {
             this.options = TypesArr[value]
         }
       }
})


new Vue({
    el: '#select1',
    data: {
           selected: 'Fruit',
           options: [ { text: 'Fruit', value: 'Fruit' }, { text: 'Meat', value: 'Meat' } ]
       },
       methods: {
         onChange: function (event)
         {
             selectTwo.update(event.srcElement.value)
         }
       }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<select v-on:change="onChange" id="select1">
    <option v-for="option in options" v-bind:value="option.value">
    {{ option.text }}
    </option>
</select>

<select id="select2">
    <option v-for="option in options" v-bind:value="option.value">
    {{ option.text }}
    </option>
</select>

다른 답은 실제로 'Vue' 답은 아니다.

이 문제를 처리하는 방법은 선택 상자로 수행할 작업에 따라 달라진다.서식의 입력은 자네가 처리해 주겠지?

두 가지 옵션:

  1. 계산 속성 사용
  2. 다른 선택 상자를 표시하려면 v-if를 사용하십시오.각 선택 상자에 다른 v-모델이 있는 경우 이상적일 수 있음

계산된 속성

<template>
 <div class="container">
    <select id="firstInput" v-model="selected">
        <option v-for="option in firstInputOptions" :value="option">
        {{ option }}
        </option>
    </select>
    <select id="secondInput" v-model="secondInputSelected">
        <option v-for="option in secondInputOptions" :value="option">
        {{ option }}
        </option>
    </select>
 </div> <!-- /container -->
</template>

<script>
export default {
  computed: {
    secondInputOptions(){
      return this.selected === 'fruit' ? this.fruit : this.vegetables
    }
  },
  data () {
    return {
      fruit: ['apple', 'banana', 'orange'],
      vegetables: ['carrot', 'beet', 'celery'],
      firstInputOptions: ['fruit', 'vegetables']
      selected: 'fruit',
      secondInputSelected: ''
    }
  },
}
</script>

조건부 렌더링

<template>
 <div class="container">
    <select id="firstInput" v-model="selected">
        <option v-for="option in firstInputOptions" :value="option">
        {{ option }}
        </option>
    </select>
    <select id="secondInputFruit" v-model="selected" v-if="selected == 'fruit'">
        <option v-for="option in secondInputOptions" :value="option">
        {{ option }}
        </option>
    </select>
    <select id="secondInputVegetables" v-model="vegetableSelected" v-else-if="selected == 'vegetables'">
        <option v-for="option in secondInputOptions" :value="option">
        {{ option }}
        </option>
    </select>
 </div> <!-- /container -->
</template>

<script>
export default {   
  data () {
    return {
      fruits: ['apple', 'banana', 'orange'],
      fruitSelected: '',
      vegetables: ['carrot', 'beet', 'celery'],
      vegetableSelected: '',
      firstInputOptions: ['fruit', 'vegetables']
      selected: 'fruit' 
    }
  },
}
</script>

순수 자바스크립트 사용

var typesArr = {fruit: ['Apple', 'Orange', 'Mango'], meat: ['Steak', 'Pork']}


function changeContext(value)
{
    if (typesArr.hasOwnProperty(value)) {
        var out = ''

        for (var i = 0; i < typesArr[value].length; i++) {
             out += '<option value="' + typesArr[value][i] + '">' + typesArr[value][i] + '</option>'
        }

        document.getElementById('select2').innerHTML = out
    }
}

changeContext('fruit')
<select onchange="changeContext(this.value)">
    <option value="fruit">Fruit</option>
    <option value="meat">Meat</option>
</select>

<select id="select2"></select>

참조URL: https://stackoverflow.com/questions/40438924/dynamically-change-select-input-options-in-vuejs-2

반응형