分享好友 前端技术首页 频道列表

vue实现导入json解析成动态el-table树表格

vue  2023-03-08 21:430

一、需求描述

前段时间接到一个需求是做一个类似接口文档的显示功能,将一段json数据贴到里面就可以自动解析出json数据的每个字段的类型和层级关系,用element组件的树表格的形式展示,并且可以手动新增、修改和删除某个数据字段。

二、界面展示

功能如下图所示:

1.未贴数据之前:

vue实现导入json解析成动态el-table树表格

2.点击右上角的‘导入json',在打开的弹框中贴入如下json数据:{"name":"lemon","sex":"女","age":18,"hobby":{"hobby1":"敲代码","hobby2":"跳恰恰"},"likeArr":["水果","青菜"]}

vue实现导入json解析成动态el-table树表格

3.点击确认后树表格自动展示贴入的json数据,如下图所示;

vue实现导入json解析成动态el-table树表格

4.点击每行的最右侧可以进行新增和删除操作;

vue实现导入json解析成动态el-table树表格

vue实现导入json解析成动态el-table树表格

5.点击tab切换到预览展示效果:

vue实现导入json解析成动态el-table树表格

三、代码实现

弹框代码展示,新建一个jsonDialog.vue文件,MonacoEditor是一个json编辑器,实现以下代码:

<template>
  <el-dialog
    title="导入 json"
    :visible.sync="dialogFormVisible"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    width="35%"
    @close="close"
    class="my_dialog"
  >
    <div class="empi_dialog_form">
      <!-- 返回 -->
      <div v-if="type == 'resp'">
        <monaco-editor v-model="jsonData" language="json" :readOnly="false"></monaco-editor>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="onSubmit()">确认</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  components: {
    MonacoEditor: () => import('@/components/MonacoEditor')
  },
  data() {
    return {
      dialogFormVisible: false,
      jsonData: null, //返回参数
    }
  },
  methods: {
    open() {
      this.dialogFormVisible = true
    },
    close() {
      this.dialogFormVisible = false
      this.jsonData = ''
    },
    // 提交
    onSubmit() {
      if (!this.jsonData) return this.$message.error('json数据不能为空')
      let flag = this.checkJson(data)
      if (flag) {
        this.dialogFormVisible = false
        this.$emit('getJson', data)
      } else {
        return this.$message.error('json数据格式不正确')
      }
    },
    // 判断是否是json格式
    checkJson(str) {
      if (typeof str == 'string') {
        try {
          let obj = JSON.parse(str)
          if (typeof obj == 'object' && obj) {
            return true
          } else {
            return false
          }
        } catch (e) {
          //console.log('error:' + str + '!!!' + e)
          return false
        }
      }
      //console.log('It is not a string!')
    }
  }
}
</script>

界面代码展示,新建一个jsonIndex.vue界面,实现以下代码:

<!-- 返回数据设置 -->
<div class="panel-item">
    <div class="panel-item-title">返回参数</div>
    <el-radio-group v-model="checkRespLabel"
        size="mini" class="radio_btn_group">
        <el-radio-button label="JSON">
        </el-radio-button>
    </el-radio-group>
    <div class="panel-item-tab">
        <div class="blue json-btn" v-show="activeTabName == 'first'" @click="addJsonClick('resp')" > 添加 </div>
        <div class="blue json-btn" v-show="activeTabName == 'first'" @click="toJsonClick('resp')"> 导入json </div>
        <el-tabs v-model="activeTabName" type="card" class="card-tab">
            <el-tab-pane label="模板" name="first">
                <el-table
                    :data="threeStepData.responseParams"
                    class="json-table"
                    :show-header="false"
                    :highlight-current-row="false"
                    row-key="id" size="medium"
                    default-expand-all
                    :tree-props="{children: 'children',hasChildren: 'hasChildren'}">
                    <el-table-column label="参数名称">
                        <template slot-scope="scopes">
                            <el-input placeholder="name" v-model="scopes.row.jsonName">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="参数类型">
                        <template slot-scope="scopes">
                            <el-select v-model="scopes.row.jsonType" placeholder="type">
                                <el-option
                                    v-for="item in typeData"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注">
                        <template slot-scope="scopes">
                            <el-input placeholder="备注" v-model="scopes.row.jsonRemark">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150">
                        <template slot-scope="scopes">
                            <el-tooltip
                                class="item"
                                effect="dark"
                                content="删除节点"
                                placement="top" :open-delay="500">
                                <i class="blue el-icon-close" @click="removeJsonClick(scopes.row, 'resp')"></i>
                            </el-tooltip>
                            <el-tooltip
                                class="item"
                                effect="dark"
                                content="添加子节点"
                                placement="top" :open-delay="500">
                                <i class="blue el-icon-plus" @click="addJsonChildrenClick(scopes.row, 'resp')"></i>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="预览" name="second">
                <div class="panel-item-content">
                    <el-input type="textarea" disabled :rows="5" v-model="strParams">
                    </el-input>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
  </div>
//弹框
<jsonDialog ref="jsonDialog" @getJson="getJson"></jsonDialog>

展示界面的功能代码,对导入json的展示及相关操作的实现:

<script>
export default {
    components: {
        MonacoEditor: () => import('@/components/MonacoEditor'),
        jsonDialog: () => import('./../dialog/jsonDialog')
    },
     data() {
        return {
            threeStepData: {
                responseParams: [
                    // {
                    //     id: 1,
                    //     jsonName: 'root',
                    //     jsonType: 'object',
                    //     jsonRemark: '备注',
                    //     pid: 0,
                    //     children: []
                    // }
                ]
            },
            checkRespLabel: 'JSON',
            activeTabName: 'first',
            typeData: [
                { label: 'string', value: 'string' },
                { label: 'number', value: 'number' },
                { label: 'array', value: 'array' },
                { label: 'object', value: 'object' },
                { label: 'boolean', value: 'boolean' }
            ]
        }
    },
    computed: {
        strParams() {
            return this.threeStepData?.responseParams
                ? JSON.stringify(this.threeStepData.responseParams)
                : '-'
        },
    },
    methods: {
        open(data) {
            this.threeStepData = data
        },
        // 导入json
        toJsonClick(type) {
            this.$refs.jsonDialog.open(type)
        },
        // 生成唯一id
        guid() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
                /[xy]/g,
                function (c) {
                    let r = (Math.random() * 16) | 0,
                        v = c == 'x' ? r : (r & 0x3) | 0x8
                    return v.toString(16)
                }
            )
        },
        // 获取json导入数据
        getJson(data, type) {
            let _data = JSON.parse(data)
            let _type = this.getJsonType(_data)
            let arr = []
            if (_type === 'object') {
                arr = this.handleJson(_data)
            }
            if (type == 'resq') {
                this.threeStepData.responseParams = arr
                // this.threeStepData.responseParams[0].children = arr
            }
        },
        // json导入数据转换
        handleJson(data) {
            let arr = []
            Object.keys(data).map((key) => {
                let _type = this.getJsonType(data[key])
                if (_type && _type == 'object') {
                    let children = this.handleJson(data[key])
                    arr.push({
                        id: this.guid(),
                        pid: data.id,
                        jsonName: key,
                        jsonType: _type,
                        jsonRemark: '',
                        children
                    })
                } else {
                    arr.push({
                        id: this.guid(),
                        jsonName: key,
                        jsonType: _type,
                        jsonRemark: ''
                    })
                }
            })
            return arr
        },
        // 判断数据类型
        getJsonType(data) {
            let type = Object.prototype.toString.call(data)
            if (type === '[object String]') {
                type = 'string'
            } else if (type === '[object Number]') {
                type = 'number'
            } else if (type === '[object Null]') {
                type = 'null'
            } else if (type === '[object Boolean]') {
                type = 'boolean'
            } else if (type === '[object Array]') {
                type = 'array'
            } else if (type === '[object Object]') {
                type = 'object'
            } else {
                type = '未进行判断的类型:' + type
            }
            return type
        },
 
        // 新增json数据
        addJsonClick(type) {
            if(type=='resp'){
                // if(this.threeStepData.responseParams?.length==1){
                //     this.$message.closeAll();
                //     this.$message.error('请勿重复添加根节点!');
                //     return;
                // }
                let obj = {
                    id: this.guid(),
                    jsonName: '',
                    jsonType: 'object',
                    jsonRemark: '',
                    // pid: 0,
                    children: []
                }
                this.threeStepData.responseParams.push(obj)
            }
        },
        //添加子节点
        addJsonChildrenClick(data, type) {
            let obj = {
                id: this.guid(),
                jsonName: '',
                jsonType: 'string',
                jsonRemark: '',
                pid: data.id
            }
           let node = this.addNode(this.threeStepData.responseParams, data.id, obj)
           if (type === 'resp') {
                this.threeStepData.responseParams = JSON.parse(JSON.stringify(node))
            }
        },
        addNode(list, pid, obj) {
            list.forEach((e) => {
                if (e.id == pid) {
                    e.children ? e.children.push(obj) : (e.children = [obj])
                } else {
                    if (e.children && e.children.length > 0) {
                        this.addNode(e.children, pid, obj)
                    }
                }
            })
            return list
        },
        // 移除json数据
        removeJsonClick(data, type) {
            let objMap = {
                resp: this.threeStepData.responseParams,
            }
            let node = this.removeItem(objMap[type], data.id)
            if (type === 'resp') {
                this.threeStepData.responseParams = JSON.parse(JSON.stringify(node))
            }
        },
        removeItem(root, id) {
            root.forEach((e, i) => {
                if (e.id === id) {
                    root.splice(i, 1)
                } else if (e.children && e.children.length > 0) {
                    this.removeItem(e.children, id)
                }
            })
            return root
        }
    }
}
</script>

综上所述,已经完成了json数据的展示、修改和新增删除都已经完成,可能有些错误,欢迎大家指正~

原文地址:https://blog.csdn.net/weixin_47978760/article/details/128718910

查看更多关于【vue】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
vue3+TS 自定义指令:长按触发绑定的函数
vue3+TS 自定义指令:长按触发绑定的函数而然间看到一个在vue2中写的长按触发事件的自定义指定,想着能不能把他copy到我的vue3项目中呢。编写自定义指令时遇到的几个难点1.自定义指令的类型在ts中写任何东西都要考虑到类型的问题,自定义指令的类型问题依然存

0评论2023-03-08326

基于ZR.VUE 前端的改造,页面刷新报错
 问题描述:前后端分离开发,分开部署. 页面刷新 直接报404 错误的解决办法提示:  先在 .env.development 中 配置 VUE_APP_BASE_API , 将 '/' 替换为 后端地址 'http://localhost:8888/'如果是对应的发布的正式环境,也要修改  .env.production 的VUE_APP_

0评论2023-03-08677

Vue3 企业级优雅实战 - 组件库框架 - 9 实现组件库 cli - 上
上文搭建了组件库 cli 的基础架子,实现了创建组件时的用户交互,但遗留了 cli/src/command/create-component.ts 中的 createNewComponent 函数,该函数要实现的功能就是上文开篇提到的 —— 创建一个组件的完整步骤。本文咱们就依次实现那些步骤。(友情提示

0评论2023-03-08947

vue-3 this概念
一、this概念官方是这样说的:在 setup()内部,this 不会是该活跃实例的引用因为 setup() 是在解析其它组件选项之前被调用的,所以 setup() 内部的 this 的行为与其它选项中的 this 完全不同这在和其它选项式 API 一起使用 setup() 时可能会导致混淆啥意思呢

0评论2023-03-08538

Vue3+TypeScript 项目中,配置 ESLint 和 Prettier
接上篇:从0搭建vite-vue3-ts项目框架:配置less+svg+pinia+vant+axios文档同步项目gitee:https://gitee.com/lixin_ajax/vue3-vite-ts-pinia-vant-less.git 一、Eslint:用于检测代码安装eslint相关依赖yarn add eslint eslint-plugin-vue @typescript-esli

0评论2023-03-08825

Vue中四种操作dom方法保姆级讲解 vue中如何操作dom
目录前言一、通过ref拿到dom的引用适用场景示例代码二、通过父容器的ref遍历拿到dom引用适用场景示例代码三、通过子组件emit传递ref适用场景示例代码四、通过:ref将dom引用放到数组中适用场景示例代码前言最近主管提出了许多优化用户体验的要求,其中很多涉及

0评论2023-03-08944

Vue状态管理工具Vuex工作原理解析 vuex五种状态
目录一、什么是vuex二、vuex的工作方式三、vuex的使用场景四、工作流程五、vuex的核心API六、应用七、vuex的工作流程一、什么是vuexVuex是vue项目的状态管理器(状态管理工具)。vue项目的状态是通过vue实例(组件)绑定的变量来体现。所以也可以说vuex是用来管理

0评论2023-03-08859

更多推荐