前提: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>