Issue
When using v-model
on an HTML <select>
, the v-model
function assigns the selected value while preserving the data types - if a number is bound to an <option>
, the model property will also be assigned as a number, and if an Object is bound, it's set accordingly.
<script>
export default {
data: {
options: [5, 10, 15, 'text', { 'description': 'I am an Object' }],
}
};
</script>
<template>
<select v-model="model">
<option
v-for="option in options"
:value="option"
>
{{ option }}
</option>
</select>
<template>
I have created a custom component called <base-select>
that wraps the usage of the <select>
tag. I'm trying to replicate the same behavior for the v-model
on this component, but I'm facing an issue where the types are not preserved - the values are consistently returned as Strings, even when binding numbers or objects.
//// BaseSelect.vue
<script>
export default {
props: {
options: {
type: Array,
required: true
},
value: {
required: true
}
},
};
</script>
<template>
<select
:value="value"
@input="$emit('input', $event.target.value)"
>
<option
v-for="option in options"
:value="option"
>
{{ option }}
</option>
</select>
</template>
//// App.vue
<script>
@import 'BaseSelect' from './BaseSelect';
export default {
components: {
BaseSelect,
},
data: {
options: [5, 10, 15, 'text', { 'description': 'I am an Object' }],
}
};
</script>
<template>
<base-select
v-model="model"
:options="options"
/>
<template>
Fiddle
To see this behavior in action, visit: http://jsfiddle.net/4o67pzLs/14/
The first select retains the data types of the values bound to the model, whereas the second one always converts values to Strings.
Query
Is there a way to implement v-model
on a custom component while preserving data types? If so, how can this be achieved?