2

在下面的代码中,我使用了一个 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
    }
  }
})
4

1 回答 1

2

v-model='select':value="select"and的简写@input="select = $event"。因此,如果要自定义发出@input事件的行为,可以将其编写为扩展形式。

在下面的代码段中,当输入值更改时,select如果它不为 null,则将其分配给,否则分配一个空字符串。

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>

于 2021-05-24T14:25:39.250 回答