vue2项目中动态的对el-table表格内容输入框字段进行校验完整代码
时间: 2024-03-27 17:39:30 浏览: 16
好的,以下是一个示例代码,可以在 Vue2 中对 el-table 的输入框字段进行校验:
```
<template>
<el-table :data="tableData">
<el-table-column prop="name" label="姓名">
<template slot-scope="scope">
<el-input v-model="scope.row.name" @blur="validateName(scope.row)" />
</template>
</el-table-column>
<el-table-column prop="age" label="年龄">
<template slot-scope="scope">
<el-input v-model.number="scope.row.age" @blur="validateAge(scope.row)" />
</template>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: "张三", age: 18 },
{ name: "李四", age: 20 }
]
};
},
methods: {
validateName(row) {
if (!row.name) {
this.$message.error("姓名不能为空");
}
},
validateAge(row) {
if (row.age && (row.age < 0 || row.age > 150)) {
this.$message.error("请输入正确的年龄");
}
}
}
};
</script>
```
在上面的代码中,我们使用了 el-table 和 el-input 组件来展示表格和输入框。对于每一个输入框,我们都添加了一个 blur 事件,在输入框失去焦点时触发校验方法。在校验方法中,我们可以使用 this.$message 方法来弹出错误提示。
需要注意的是,如果要对输入框的值进行校验,必须将输入框的值绑定到行数据的属性上,即使用 v-model 指令将输入框的值绑定到 scope.row 对象的属性上。在校验方法中,我们可以直接访问行数据对象,从而获取输入框中的值进行校验。同时,为了保证输入框中的值是数字类型,我们在绑定 v-model 时使用了 v-model.number 指令。