我的应用使用以下类型的数据: 有些公司每个都有一个数据点列表。 每个数据点都有一种类型,每个公司只能有一种类型的数据点。
+Company_1
|
|--Datapoint_1 : type_1
|--Datapoint_2 : type_2
|--Datapoint_3 : type_3
|
|
+Company_2
|
|--Datapoint_4 : type_3
|--Datapoint_5 : type_2
|
|+Company_3
|
|--Datapoint_6 : type_2
...
...
总共有大约 1000 个数据点和 20 家公司。 该应用程序根据这些数据点计算分析,目标是允许用户操纵这些数据点,以查看给定场景中的结果。 在任何给定时刻,都有一个“selected_company”和“selected_type”,基于这两个选择,应该选择正确的数据点进行操作。
我意识到,如果“companies”变量和“datapoints”属性是数组,则必须对所有项目进行搜索才能找到正确的项目。 因此,我选择将它们设为对象:
companies = {
'1' : {
name : 'Company_1',
datapoints : {
'type_1' : { ... },
'type_2' : { ... },
'type_3' : { ... }
}
},
'2' : {...},
'3' : {...},
.
.
.
}
问题:
我有一个“数据点”组件,我将数据点作为 Prop 传递:
<datum-comp :datum="companies[selected_company].datapoints[selected_type]"></datum-comp>
在此组件中,我有一个用于操作数据点的得分属性的输入:
<input v-model.number="datum.score" class="form-control">
但是,此输入表现出非常奇怪的行为。当我输入时,模型不会立即更新。相反,Vue 似乎在等待我在更新模型之前从输入 (onBlur) 改变焦点。
更奇怪的是,当我将 datapoints 属性设为数组时
companies = {
'1' : {
name : 'Company_1',
datapoints : [
{ ... },
{ ... },
{ ... }
]
},
并使用一种方法来检索数据点(而不是直接将其传入),Vue 以正确的方式运行!
<datum-comp :datum="getDatum(selected_company, selected_type)"></datum-comp>
(在 js 文件中:)
var app = new Vue({
el : '#app',
data:{...},
methods:{
getDatum: function(selected_company, selected_type){
var datum = this.companies[selected_company].datapoints.find(function(elem){
return elem.type == selected_type
})
return datun
}
}
})
我需要帮助来理解为什么 Vue 在这些情况下表现如此,因为它对应用程序性能有一些严重影响。 提前致谢。
最佳答案
v-model
就是 syntax sugar for ...
:value="modelValue"@input="modelValue = $event.target.value"
正如你所说,它更新了模型oninput ,大多数情况下效果很好。
如果您想要其他东西,这很容易做到。只需将更新端更改为 onkeypress,所以...
<input class="form-control
:value="datum.score"
@keypress="datum.score = $event.target.value""
@input="datum.score = $event.target.value""
>
当您将数据点从数组更改为对象时,您注意到的变化可能是由于 Vue cannot detect changes made in an array using array syntax (方括号)。您需要使用数组方法(push、pop、splice 等)或 Vue.set()。就像你说的,这不直观,但它是 Vue 中为数不多的陷阱之一。这是由于 javascript 的限制,并且在文档中有很好的介绍。
关于vue.js - 为什么 Vuejs 在输入失去焦点之前不更新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48855281/