In the code below I am using a v-autocomplete component
and a variable select
where the selected value is stored.
The watch
logs the value and type of select
.
The problem I'm facing is that when the text typed in the v-autocomplete is cleared, select
defaults to null instead of an empty string.
Is there any way to revert select
to an empty string instead of a null object?
<div id="app">
<v-app id="inspire">
<v-card>
<v-container fluid>
<v-row
align="center"
>
<v-col cols="12">
<v-autocomplete
v-model="select"
:items="items"
dense
filled
label="Filled"
clearable
></v-autocomplete>
</v-col>
</v-row>
</v-container>
</v-card>
</v-app>
</div>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
items: ['foo', 'bar', 'fizz', 'buzz'],
select: "",
}),
watch:{
value:function(value){
console.log(this.select) // select value
console.log(typeof(this.value)); // select variable type
}
}
})
v-model='select'
is a shorthand for :value="select"
and @input="select = $event"
. Thus, if you want to customize the behaviour of emitted @input
event, you can write it in expanded form.
In below snippet, when the input value changes, you assign it to select
if it is not null, or assign an empty string otherwise.
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
items: ['foo', 'bar', 'fizz', 'buzz'],
select: "",
}),
watch:{
select:function(value){
console.log(value) // select value
console.log(typeof(value)); // select variable type
}
}
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<div id="app">
<v-app id="inspire">
<v-card>
<v-container fluid>
<v-row
align="center"
>
<v-col cols="12">
<v-autocomplete
:value="select"
@input="select = $event || ''"
:items="items"
dense
filled
label="Filled"
clearable
></v-autocomplete>
</v-col>
</v-row>
</v-container>
</v-card>
</v-app>
</div>