vue select option get attribute

<template>
  <div>
    <select v-model="selectedOption" @change="handleChange">
      <option v-for="option in options" :key="option.id" :value="option.id" :data-attribute="option.attribute">
        {{ option.label }}
      </option>
    </select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedOption: null,
      options: [
        { id: 1, label: 'Option 1', attribute: 'Attribute 1' },
        { id: 2, label: 'Option 2', attribute: 'Attribute 2' },
        { id: 3, label: 'Option 3', attribute: 'Attribute 3' }
      ]
    };
  },
  methods: {
    handleChange() {
      const selectedOption = this.options.find(option => option.id === this.selectedOption);
      const attributeValue = selectedOption ? selectedOption.attribute : null;
      console.log('Selected Option Attribute:', attributeValue);
    }
  }
};
</script>

In this example:

  1. A select element is defined with v-model bound to the selectedOption data property and an @change event listener triggering the handleChange method.
  2. Inside the select element, a loop using v-for iterates over the options array, creating an option for each item. The :value binding sets the selected value to the id property of each option, and :data-attribute binds a custom data attribute to each option using the attribute property.
  3. The handleChange method is triggered when the selected option changes. It retrieves the selected option object from the options array using find based on the id matching the selectedOption.
  4. The attribute value of the selected option is obtained and logged to the console. If no option is selected, null is logged.