vue2.x使用jsoneditor编辑器

前提:vue项目,需要能方便的管理和编辑json格式的数据。目前我的设计是,有一个名为“配置json”的按钮,点击后打开一个el-dialog的弹框,包含着这个json编辑框。点击“提交”时把数据传出,点击“取消”关闭弹框并销毁弹框。

依赖项

JSON Editor GitHub 英文文档:https://github.com/jdorn/json-editor

2022年4月19日,安装的依赖包是9.7.4的版本

安装

cnpm install jsoneditor -S

使用

index.vue

<template>
	<el-button plain @click="configJson(jsonItems)">配置{{jsonItems[0].title}}</el-button>
</template>

<script>
import ConfigJSON from '../components/ConfigJSON.vue'
// 这里的exprot default写法是复制了项目里的,我就没改。其中的内容可以参考
export default { 
  data() {
    return {
      jsonItems: [],
    }
  },
  methods: {
    configJson(json) {
        //这里传进来的json是这样的,{"a": "111", "b": "222"}
        const configModel = new Vue(ConfigJSON)
        configModel.open(json).then((result) => {
          console.log(result)
        })
      } 
   }
}
</script>

ConfigJSON.vue

<template>
  <el-dialog :visible.sync="dialogVisible" :destroy-on-close="destroyOnClose" :close-on-click-modal="closeOnClickModal" v-if="dialogVisible">
    <div id="jsonEditor" style="height:100%"></div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import JSONEditor from 'jsoneditor'
import 'jsoneditor/dist/jsoneditor.css'

let editor = null
export default {
  name: 'ConfigJSON',
  components: {
    JSONEditor,
  },
  props: {
    dialogVisible: { type: Boolean, default: true },
    jsonData: { type: Object },
  },
  data() {
    return {
      destroyOnClose: true,
      closeOnClickModal: false,
      options: {
        mode: 'code',
        search: false,
        transform: false,
      },
    }
  },
  mounted() {
    this.$nextTick(() => {
      const container = document.getElementById('jsonEditor')
      editor = new JSONEditor(container, this.options)
      editor.set(this.jsonData)
    })
  },

  methods: {
    onSubmit() {
      this.jsonData = editor.get()
      this.$emit('submit', this.jsonData)
    },
    open(data) {
      this.jsonData = JSON.parse(JSON.stringify(data))
      this.$mount()
      document.body.appendChild(this.$el)
      return new Promise((resolve) => {
        this.$on('submit', (newValue) => {
          this.dialogVisible = false
          resolve(newValue)
        })
      })
    },
  },
}
</script>

<style>
.jsoneditor .jsoneditor-transform,
.jsoneditor .jsoneditor-repair,
.jsoneditor .jsoneditor-poweredBy {
  display: none;
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值