在下面的代码中我使用了 v-autocomplete 组件
以及存储所选值的变量select
。
watch
记录 select
的值和类型。
我面临的问题是,当清除 v-autocomplete 中输入的文本时,select
默认为 null 而不是空字符串。
有没有办法将 select
恢复为空字符串而不是空对象?
<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'
是 :value="select"
和 @input="select = $event"
的简写>。因此,如果您想自定义发出的 @input
事件的行为,您可以以扩展形式编写它。
在下面的代码片段中,当输入值更改时,如果它不为 null,则将其分配给 select
,否则分配一个空字符串。
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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47212829330773693f" rel="noreferrer noopener nofollow">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0a6a5b5a4b9b6a990e2fea8" rel="noreferrer noopener nofollow">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86f0f3e3c6b4a8fe" rel="noreferrer noopener nofollow">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d4b485849545b447d0f1345" rel="noreferrer noopener nofollow">[email protected]</a>/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>
关于javascript - Vuetify 的 v-autocomplete 组件在清除时将 v-model 值重置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67673324/