Search code examples
vue.jsselectv-for

Clearing Vue JS v-for Select Field


I have a simple application that uses a v-for in a select statement that generates two select tags. The groupedSKUAttributes variable that creates the select statement looks like this:

groupedSKUAttributes = {colour: [{id: 1, name: 'colour', value: 'red'},
                                 {id: 2, name: 'colour', value: 'blue'}],
                        size: [{id: 3, name: 'size', value: '40'},
                               {id: 4, name: 'size', value: '42'}]}

I also have a button that I want to clear the select fields. How do I get the clear method to make each of the select fields choose their default <option value='null' selected>select a {{ attributeName }}</option> value? I can't figure out if I'm meant to use a v-model here for the groupedSKUAttributes. Any advice would be appreciated.

The template looks like this:

<template>
  <div>
    <select
      v-for='(attribute, attributeName) in groupedSKUAttributes'
      :key='attribute'
      @change='update(attributeName, $event.target.value)'>
      <option value='null' selected>select a {{ attributeName }}</option>
      <option
        v-for='a in attribute'
        :value='a.id'
        :label='a.value'
        :key='a.id'>
      </option>
    </select>
  </div>
  <button @click='clear'>clear</button>
</template>

And the JS script looks like this:

<script>
export default {
  name: 'app',
  data() {
    return {
      groupedSKUAttributes: null,
    }
  },
  methods: {
    clear() {
      console.log('clear');
    },
    update(attributeName, attributeValue) {
      console.log(attributeName, attributeValue);
    },
    getSKUAttributes() {
      API
        .get('/sku_attribute/get')
        .then((res) => {
          this.skuAttributes = res.data;
          this.groupedSKUAttributes = this.groupBy(this.skuAttributes, 'name');
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getSKUAttributes();
  }
}
</script>

Solution

  • The v-model directive works within the v-for without any issues.

    <script>
      export default {
        name: 'app',
    
        data() {
          return {
            groupedSKUAttributes: null,
            selected: {}
          }
        },
    
        methods: {
          clear() {
            this.generateDefaultSelected(this.generateDefaultSelected);
          },
          update(attributeName, attributeValue) {
            this.selected[attributeName] = attributeValue;
          },
          getSKUAttributes() {
            API
              .get('/sku_attribute/get')
              .then((res) => {
                this.skuAttributes = res.data;
                this.groupedSKUAttributes = this.groupBy(this.skuAttributes, 'name');
    
                // Call this method to reset v-model
                this.generateDefaultSelected(this.groupedSKUAttributes);
              })
              .catch((error) => {
                console.error(error);
              });
          },
    
          generateDefaultSelected(groupedSKUAttributes) {
            // Reset the object that maintains the v-model reference;
            this.selected = {};
    
            Object.keys(groupedSKUAttributes).forEach((name) => {
              // Or, set it to the default value, you need to select
              this.selected[name] = '';
            });
          }
        },
    
        created() {
          this.getSKUAttributes();
        }
      }
    </script>
    

    In the above code, generateDefaultSelected method resets the selected object that maintains the v-model for all your selects.

    In the template, you can use v-model or unidirectional value/@change pair:

    <!-- Using v-model -->
    <select
      v-for='(attribute, attributeName) in groupedSKUAttributes'
      :key='attributeName' v-model="selected[attributeName]">
    
    
    <!-- Unidirection flow without v-model -->
    <select
      v-for='(attribute, attributeName) in groupedSKUAttributes'
      :key='attributeName' :value="selected[attributeName]"
      @change='update(attributeName, $event.target.value)'>