【问题标题】:Why doesn't combobox update edited item model?为什么组合框不更新已编辑的项目模型?
【发布时间】:2020-12-14 12:45:22
【问题描述】:

组合框是这样定义的:

<template>
   <v-combobox
   clearable
   v-model="values"
   :items="items"
   item-text="name"
   ></v-combobox>
</template>

<script>
data () {
    return {
        items: [
            {"id": 2, "name": "tree"},
            {"id": 4, "name": "grass"},
            {"id": 5, "name": "freeze"},
            {"id": 9, "name": "moss"}
        ],
        values: ''
    },
    watch: {
        values () {
            console.log(this.values) // Output: {__ob__: Observer}: e.g. id: 2, name: tree
        }
    }
}
</script>

组合框项目是可编辑的:我可以选择其中一个(然后观察者登录到控制台),然后编辑它,但控制台中没有任何反应。

如何使用已编辑的条目更新模型?

编辑:刚刚发现模型在离开组合框字段 (onBlur) 时得到更新。如何将此行为更改为例如onKeyDown?

EDIT2:另一个发现:在组合框外单击时,values 被重置(未定义)。因此,只能考虑 onChange 事件。

【问题讨论】:

    标签: vue.js combobox vuetify.js


    【解决方案1】:

    item-value 属性缺失,你可以这样做:

     items: [
                {"id": 2, "name": "tree", "value" : 1},
                {"id": 4, "name": "grass", "value" : 2},
                {"id": 5, "name": "freeze", "value" : 3},
                {"id": 9, "name": "moss", "value" : 4}
            ],
    

    在你的标签中

      <v-combobox
       clearable
       v-model="values"
       :items="items"
       item-text="name"
       item-value = "value"
       @change = "values()"
       ></v-combobox>
    

    【讨论】:

    • 我添加了item-value="id",但它并没有改变模型更新问题......不过,模型在离开组合框字段时得到更新,而不是在改变它的值时。
    • 编辑了答案,在标签中添加了@change,再试一次
    • 这个values() 条目指的是什么?它是对模型values 的引用吗?不幸的是,我收到了一个错误:Error in v-on handler: "TypeError: _vm.values is not a function"
    【解决方案2】:

    我想出了如何解决它,但我认为它不是一个优雅的解决方法。

    为了清楚起见:我需要将 idname 都传递给 comboboxid 是只读的,而 name 条目必须是可编辑的。 id 被传递给 values 模型,这要归功于 item-value="id" 添加到 combobox 定义中(它已经在 Germano Buss Niehues 的回答下面的讨论中评论过)。 name 仅在选择项目时由模型更新,但在编辑后不更新。而name的编辑值正是我所需要的。

    最终,我将纯 HTML id 字段添加到 combobox

    <template>
       <v-combobox
         clearable
         id="words_names"
         v-model="values"
         :items="items"
         item-text="name"
       ></v-combobox>
    </template>
    

    并使用以下命令读取最终值:

    document.getElementById("words_names").value

    正如我所说,不是很优雅,但它的工作......

    【讨论】:

      猜你喜欢
      • 2017-07-14
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多