<template> <div class="app-form-json"> <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="CurrentVal"> </el-input> <div id='editor_holder_json'></div> </div> </template> <script lang="ts"> import { Component, Vue, Prop, Model, Watch } from "vue-property-decorator"; import { VNode, CreateElement } from "vue"; import { interval, Subject, Subscription } from "rxjs"; import JSONEditor from "@json-editor/json-editor"; import BootstrapVue from "bootstrap-vue"; import "bootstrap/dist/css/bootstrap.css"; import "bootstrap-vue/dist/bootstrap-vue.css"; import "../app-form-json/app-form-json.less"; @Component({}) export default class AppFormJson extends Vue { /** * 双向绑定值 * * @type {*} * @memberof AppFormJson */ @Model("change") itemValue?: any; /** * 表单数据 * * @type {*} * @memberof AppFormJson */ @Prop() public data!: any; /** * 数据格式 * * @type {*} * @memberof AppFormJson */ @Prop() public schema?: any; /** * 格式选项 * * @type {*} * @memberof AppFormJson */ @Prop() public options?: any; /** * 当前值 * * @return {*} * @memberof AppFormJson */ get CurrentVal() { return this.itemValue; } /** * 设置值 * * @param {*} [value] * @memberof AppFormJson */ set CurrentVal(val: any) { this.$emit("change", val); } /** * 表单状态 * * @type {Subject<any>} * @memberof AppFormJson */ @Prop() public formState?: Subject<any>; /** * 表单状态事件 * * @private * @type {(Unsubscribable | undefined)} * @memberof AppFormJson */ private formStateEvent: Subscription | undefined; /** * Vue生命周期(实例销毁后) * * @memberof AppFormJson */ public destroyed() { if (this.editor) this.editor = null; } /** * Vue生命周期(实例挂载后) * * @memberof AppFormJson */ public mounted() { if (!this.formState) { return; } this.formStateEvent = this.formState.subscribe(($event: any) => { if (Object.is($event.type, "load")) { this.renderJsoneditor(); } }); } /** * 编辑器对象 * * @type {*} * @memberof AppFormJson */ public editor: any; public getSchema(): any{ if(this.schema) return this.schema; else return {}; } public getOptions(): any{ let _options={ theme: "bootstrap3", iconlib: "fontawesome4", disable_edit_json: true, display_required_only: true, disable_collapse: true, disable_array_delete_last_row: true, ajax: true, }; _options["schema"]=this.getSchema(); if (this.CurrentVal) { _options["startval"] = JSON.parse(this.CurrentVal); } if(this.options){ return Object.assign({},_options,this.options) } return _options; } /** * 编辑器生成 * * @memberof AppFormJson */ public renderJsoneditor() { var _this = this; var element = document.getElementById("editor_holder_json"); if (this.editor) { this.editor.destroy(); } this.editor = new JSONEditor(element, _this.getOptions()); this.editor.on("change", () => { let value = _this.editor.getValue(); _this.CurrentVal = JSON.stringify(value); }); } /** * 设置编辑器值 * * @param {*} [val] * @memberof AppFormJson */ public setEditValue(val: any): void { if (val) { this.editor.setValue(val); } else { this.editor.setValue({}); } } } </script>