创新项目实训
任务
已经实现了大部分数据的可视化,现在有了新的需求,如何实现对图表的结构化数据进行在线编辑,并能够实时运行展示,并保存到数据库中,因此我们需要实现一个在线编辑器,并能够对图表进行实时更新。
vue-codemirror
- 介绍,就不多说了,请看官网,下面介绍实现对JSON的在线编辑(与常规的vue-codemirror略有不同),可以参考文章
- 引入各种样式,语言等信息
// require styles import 'codemirror/lib/codemirror.css' // 引入语言 import 'codemirror/mode/javascript/javascript.js' // 引入样式 import 'codemirror/theme/juejin.css' import 'codemirror/theme/rubyblue.css' import 'codemirror/theme/idea.css' // JSON import 'codemirror/addon/lint/lint.css' import 'codemirror/addon/lint/json-lint' import CodeMirror from 'codemirror'
- 定义容器
<div class="json-editor"> <textarea ref="textarea" /> </div>
- 容器初始化
initEditor() { this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, { lineNumbers: true, mode: 'application/json', gutters: ['CodeMirror-lint-markers'], theme: 'idea', lint: true, }); // 设置编辑器值 this.jsonEditor.setValue(this.value); console.log(this.value) this.jsonEditor.on('change', cm => { this.$emit('changed', cm.getValue()); this.$emit('input', cm.getValue()); }); },
- 定义出其他方法
getValue () { //获得编辑器中的内容 return this.jsonEditor.getValue() },
- 实现效果
图表的实时更新
- 对图表的生命周期了解即可。如init,setOption,dispose等。
//运行代码 runCode(){ let code = this.getValue() this.dataClean(code) console.log(this.chartType) this.handleOptionBeforeSet() this.chartInstance.setOption(this.decoration); //this.chartInstance.setOption(code) },
图表相关信息的保存
- 常规操作,调用后端接口即可。
submitUpdateChartData(){ this.$confirm('此操作将永久修改图表配置, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { updateChartData({data:{chartId:this.chartInfo.id,chartData:this.getValue()}}).then(response=>{ if(response.data===1){ this.$message({ type: 'success', message: '修改成功!' }); }else{ this.$message({ type: 'warning', message: '修改失败!' }); } }) }).catch(() => { this.$message({ type: 'info', message: '已取消更新' }); }); }, submitUpdateChartInfo(){ this.$confirm('此操作将永久修改图表信息, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { updateChartInfo({data:{chartId:this.chartInfo.id,chartName:this.updateForm.name,genResult:this.updateForm.result}}).then(response=>{ if(response.data===1){ this.$message({ type: 'success', message: '修改成功!' }); this.dialogVisible=false }else{ this.$message({ type: 'warning', message: '修改失败!' }); } }) }).catch(() => { this.$message({ type: 'info', message: '已取消更新' }); }); },
- 页面展示