一:需求
1.需要实现主表格
的expand和编辑
功能
2.嵌套的子表格
不是纯展示字段,需要对内容进行编辑
3.在主页提交表格数据时,需要同时保存
主表格和子表格的数据,并且对所有的数据进行校验
二:expand功能的实现方式
1.实现表格的嵌套
1.新建一个ExpandTable.vue
页面,作为嵌套的子表格
2.在Index.vue
主页面中进行引用
3.render 方法中需要使用this.$createElement
添加ref,而不能使用h
,否则this.$refs将访问不到数据
{
type: 'expand',
width: 50,
render: (h, params) => {
return this.$createElement(ExpandTable, {
ref: `caseList${params.index}`,
props: {
scriptId: params.row.script, // 传参
},
})
},
},
2.在主页中获取到子表格的数据
1.在ExpandTable.vue
页面中传出:子表格的数据
// 传出数据给父组件
pushData () {
return this.tableList
},
2.在Index.vue
主页面中获取到子表格的数据,并且遍历主表格,把子表格的数据加入到主表格中
// 处理主、子表格的数据
dealData () {
const data = this.tableList.map((item, index) => {
return {
name: item.name, //主表格的字段
childDatas: this.$refs[`caseList${index}`].pushData(), // 获取子表格的数据
}
})
},
3.手动处理:能否展开
1.禁用表格某一行的展开功能
this.tableList[index]._disableExpand = true
this.tableList[index]._expanded = false
2.启用表格某一行的展开功能
this.tableList[index]._disableExpand = false
this.tableList[index]._expanded = true
三:编辑的实现方式
1.需要修改的字段,使用插槽
<template
slot-scope='{ row, index }'
slot='port'
>
<Input
v-model='row.port'
placeholder='请输入'
@on-change='setValue(row.port, index, "port")'
:class="{'ivu-form-item-error':checkValue(row.port)}"
/>
</template>
2.将输入框的值放入 table 中
// 修改表格数据
setValue (value, index, KeyName) {
this.tableList[index][KeyName] = value
},
3.对输入框中的值进行校验,如果不符,给输入框加入ivu-form-item-error
的样式
// 校验输入框的值
checkValue (value) {
if (!value) return true //校验必填
},
4.在提交时,获取到页面中ivu-form-item-error
的类名的长度
- 若为0,说明所有的数据都符合校验,可以调用接口进行提交;
- 若不为0,不进入接口调用的函数;
- 初始化时,需要使用
nextTick
进行校验
// 提交
handleSubmit () {
this.isSubmit = true
this.$nextTick(() => {
const fillValid = !document.getElementsByClassName('ivu-form-item-error').length // 检测对象校验结构
this.$refs.formData.validate(valid => {
if (valid && fillValid) {
this.addData() // 新增
}
})
})
},