基于 vue2.X 和 vue-table-with-tree-grid 实现的一个接口管理组件


外圆内方 2019-1-20 Vue vue-table-with-tree-grid 接口管理

需求初衷

后台老大用小幺鸡码文档很不爽,要一个一个往上去写。他想搞个工具从后台生成 json。但是不能都看 json 字符串去,要能看到层级结构,还要能偶尔的改动一下。就花了几天时间做了个接口管理系统。这个是主要的新增编辑详情页面组件。

预览

后台工具生成的返回参数: 图 1

编辑返回参数,新加一条"用户组权限等级" 图 2

确认后在表格展示并提交修改 图 3

主要问题在于数据结构的转换,以图片数据为例:

  1. 这是表格需要的数据格式
const table = [
	{ key: "msg", value: "true||string||消息" },
	{ key: "code", value: "true||number||code码" },
	{
		key: "data",
		value: "",
		children: [
			{
				key: "result",
				value: "",
				children: [
					{
						key: "companyId",
						value: "true||string||公司id"
					},
					{
						key: "userGroupList",
						value: "",
						children: [
							{
								key: "userGroupId",
								value: "true||string||用户组ID"
							},
							{
								key: "groupName",
								value: "true||string||用户组名字"
							}
						]
					}
				]
			}
		]
	}
]

json 转 table :

jsonTurnTable (data) {
    const result = []
    function recursive (data, arr) {
        for (let i in data) {
            if (typeof data[i] === 'object') {
                if (Object.prototype.toString.call(data[i]) === '[object Array]') {
                    arr.push({ key: i, value: '', children: data[i], $thisNodeType: 'array' })
                    data[i].forEach(j => {
                        const obj = Object.assign({}, j)
                        arr[arr.length - 1].children = []
                        recursive(obj, arr[arr.length - 1].children)
                    })
                } else {
                    arr.push({ key: i, value: '', children: [data[i]], $thisNodeType: 'object' })
                    const obj = data[i]
                    arr[arr.length - 1].children = []
                    recursive(obj, arr[arr.length - 1].children)
                }
            } else {
                arr.push({ key: i, value: data[i], $thisNodeType: 'string' })
            }
        }
    }
    recursive(data, result)
    return result
}
  1. 这是后台生成的 json 数据格式
{
    "msg":"true||string||消息",
    "code":"true||number||code码",
    "data":{
        "result":[{
            "companyId":"true||string||公司id",
            "userGroupList":[{
                "userGroupId":"true||string||用户组ID",
                "groupName":"true||string||用户组名字"
            }]
        }]
    }
}

table 转 json :

tableTurnJson (data) {
    const result = {}
    function recursive (data, obj) {
        data.forEach(i => {
            if (i.$thisNodeType === 'array') {
                const { key } = i
                obj[key] = [{}]
                recursive(i.children, obj[i.key][0])
            } else if (i.$thisNodeType === 'object') {
                const { key, children } = i
                obj[key] = {}
                recursive(children, obj[key])
            } else {
                obj[i.key] = i.value
            }
        })
    }
    recursive(data, result)
    return result
}

github 地址:VUE-ApiMAanagement-Component