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:
- A
select
element is defined withv-model
bound to theselectedOption
data property and an@change
event listener triggering thehandleChange
method. - Inside the
select
element, a loop usingv-for
iterates over theoptions
array, creating anoption
for each item. The:value
binding sets the selected value to theid
property of each option, and:data-attribute
binds a custom data attribute to each option using theattribute
property. - The
handleChange
method is triggered when the selected option changes. It retrieves the selected option object from theoptions
array usingfind
based on theid
matching theselectedOption
. - The attribute value of the selected option is obtained and logged to the console. If no option is selected,
null
is logged.