在下面的代码中,我使用了一个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
}
}
})发布于 2021-05-24 22:25:39
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/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/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>
https://stackoverflow.com/questions/67673324
复制相似问题