Home > database >  assign value to select in methods in vuejs?
assign value to select in methods in vuejs?

Time:10-14

<a-radio-group
  @change="changeName"
  v-decorator="[
                'name',
                { initialValue: 'light' },
                ]"
>
  <a-radio value="iphone">Iphone</a-radio>
  <a-radio value="samsung">Samsung</a-radio>
</a-radio-group>
   

<a-form-item label="Value" :colon="false">
  <a-select placeholder="Select a value">
    <a-select-option></a-select-option>
  </a-select>
</a-form-item>
methods: {
  changeName(event) {
    var value = event.target.value;
    if (value == 'iphone') {
      // I want to assign the select-option the value : 
      //<a-select-option value="ip12">Iphone 12</a-select-option>
      // <a-select-option value="ip13">Iphone 13</a-select-option>
    } else {
      //<a-select-option value="ss10">Samsung note 10</a-select-option>
      // <a-select-option value="ss9">Samsung note 9</a-select-option>
    }
  }
}

How do I change the <a-select-option>s when I select a radio button?

CodePudding user response:

You can compute the <a-select>'s options based on the <a-radio-group>'s value.

  1. Instead of the change-event handler, use a v-model directive on the <a-radio-group> to store the selected brand, and on the <a-select> to store the selected phone:

    <template>
      <a-radio-group v-model="selectedBrand">
        <!-- brands -->
      </a-radio-group>
    
      <a-select placeholder="Select a value" v-model="selectedPhone">
        <!-- phone options -->
      </a-select>
    </template>
    
    <script>
    export default {
      data () {
        return {
          selectedBrand: '',
          selectedPhone: '',
        }
      }
    }
    </script>
    
  2. Add a computed property for the options to show based on the selected brand:

    const PHONE_OPTIONS = {
      iphone: [
        { value: 'iph12', label: 'Iphone 12' },
        { value: 'iph13', label: 'Iphone 13' },
      ],
      samsung: [
        { value: 'ss10', label: 'Samsung Note 10' },
        { value: 'ss9', label: 'Samsung Note 9' },
      ],
    }
    
    export default {
      computed: {
        phoneOptions() {
          return PHONE_OPTIONS[this.selectedBrand]
        },
      },
    }
    
  3. Use a watcher on the phone options to automatically select the first one.

    export default {
      watch: {
        phoneOptions(value) {
          this.selectedPhone = value?.[0].value
        },
      },
    }
    
  4. Render the phone options:

    <a-select-option v-for="opt in phoneOptions" :key="opt.value" :value="opt.value">
      {{ opt.label }}
    </a-select-option>
    

demo

  • Related