我在我的项目中使用了引导表。这些字段填充在
computed
,例如
<b-table :items="items" :fields="tableFields">...</b-table>
computed: {
tableFields() {
const result = [
{
key: "status",
label: "Status",
},
{
key: "name",
label: "Name",
},
{
key: "weight",
label: "Weight",
},
];
return result;
},
},
我的数据中有一些变量,例如:
data() {
return {
validationErrors: {},
};
},
validationErrors
在方法中更新,例如:
methods: {
validateInput(data) {
const id = data.item.id;
const value = data.item.weight;
this.validationErrors[id] = "";
if (value === "") {
this.validationErrors[id] = "Weight is required";
} else if (value < 1) {
this.validationErrors[id] = "Value should be equal or greater than 1";
} else if (value > 100) {
this.validationErrors[id] = "Value cannot be greater than 100";
}
}
saveWeight() {
// Validate all inputs before proceeding
this.items.forEach((item) => {
this.validateInput({ item: item });
});
},
}
这两个方法是从两个 html 元素触发的,例如:
<b-table :items="items" :fields="tableFields">
<template v-slot:cell(weight)="data">
<b-form-input
v-model="data.item.weight"
type="number"
min="1"
max="100"
@input="validateInput(data)"
/>
<small>
{{ validationErrors[data.item.id] }}
</small>
</template>
</b-table>
{{ validationErrors }} // keep it for demo purpose
<b-button
variant="primary"
:disabled="hasvalidationErrors || !isTotalValid"
@click="saveWeight()"
>
Save
</b-button>
因此,当用户更改输入内容或按下保存按钮时,这两种情况都会检查验证规则,如果存在任何验证错误,这些错误将存储在
validationErrors
中。问题是,最初当输入具有无效值(在本例中为 0),并且用户不与任何输入元素交互并且用户直接单击保存按钮时;那么 updated validationErrors
不会显示在表格内;但它在表外正确显示。
这是我的演示的屏幕截图。红色标记部分显示初始值,绿色标记部分显示更新值:
表内的
validationErrors
仅当用户更改任何输入的值时才会更新。我不明白为什么在桌子外面它可以工作,而在桌子里面却不起作用!是因为从computed
填充表格的字段吗?我该如何解决这个问题?
这是关于在 vue 2 中创建响应式 props。如果安装组件时
validationErrors
对象中不存在该属性,那么要创建它并使其响应式,您应该使用 this.$set()
实用程序方法。在 validateInput
方法中,您应该检查该属性是否存在,然后像上面提到的那样创建它:
validateInput(data) {
const id = data.item.id;
const value = data.item.weight;
if (!this.validationErrors[id])
this.$set(this.validationErrors, id, "");
// rest of the code
}
我应该指出,使用您当前的代码,即使在用户更新输入之后,
validationErrors
属性仍然保持不反应状态,模板的重新呈现很可能是由表格单元格数据的更新触发的。
PS:克服反应性问题的另一种方法是重新分配整个更新的对象。喜欢:
validateInput(data) {
const id = data.item.id;
const value = data.item.weight;
// Clone the validationErrors object
let errors = JSON.parse(JSON.stringify(this.validationErrors))
// update the errors object instead of this.validationErrors
// ...
// Reassign the updated object at the end
this.validationErrors = errors
}