【问题标题】:Vuetify's v-autocomplete component resets the v-model value to null when clearedVuetify 的 v-autocomplete 组件在清除时将 v-model 值重置为 null
【发布时间】:2021-05-24 13:56:41
【问题描述】:

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

【问题讨论】:

    标签: javascript vue.js vuetify.js v-autocomplete


    【解决方案1】:

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

    在sn-p下面,当输入值发生变化时,如果不为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>

    【讨论】:

    • 这就像一个魅力。非常感谢。我一直在寻找解决这个问题的方法。
    猜你喜欢
    • 1970-01-01
    • 2021-11-19
    • 2021-05-02
    • 1970-01-01
    • 2020-08-28
    • 2021-12-03
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    相关资源
    最近更新 更多