<template>
    <div style="width: 100%">
        <el-button type="primary" style="margin-bottom: 10px" size="small" @click="formatCode">格式化JSON</el-button>

        <b-code-editor
            v-model="jsonData"
            :auto-format="true"
            :smart-indent="true"
            theme="dracula"
            :indent-unit="4"
            :line-wrap="true"
            ref="editor"
        ></b-code-editor>
        <br />
    </div>
</template>
 
<script>
export default {
    data() {
        return {
            jsonData: '',
        }
    },
    methods: {
        // 检测json格式
        isJSON(str) {
            if (typeof str == 'string') {
                try {
                    var obj = JSON.parse(str)
                    if (typeof obj == 'object' && obj) {
                        return true
                    } else {
                        return false
                    }
                } catch (e) {
                    return false
                }
            } else if (typeof str == 'object' && str) {
                return true
            }
        },
        onSubumit() {
            if (!this.isJSON(this.jsonData)) {
                this.$message.error(`json格式错误`)
                return false
            }
            console.log(JSON.parse(this.jsonData))
            return true
        },
        formatCode() {
            this.$refs.editor.formatCode()
        },
    },
}
</script>
 
<style>
.bin-json-editor {
    height: 500px !important;
}
.CodeMirror {
    height: 500px !important;
}
</style>